您的位置 首页 golang

从底层深入Go的基础模型 – interface

作者:得物技术

出处:

interface

In Object-oriented programming, a protocol or interface is a common means for unrelated Object (computer science) to communicate with each other. These are definitions of Method (computer programming) and values which the objects agree upon in order to co-operate. —— wiki

从底层深入Go的基础模型 - interface

0 interface是什么

在wiki中是这样定义的,interface和protocol类似,都是双方为了交流而作出的约定。

直接拿这套定义去理解 Go lang中的interface可能难以理解,那么可以换种说法,即interface就像包饺子。

具体类型就像饺子馅,而预先定义的接口则就是饺子皮,也就是对具体类型进行了一层封装后,放入桌上(itabTable),随需随拿。最后吃的仍然是馅。

(真正使用的仍然是接口中包着的具体类型方法)

01.

为什么要使用interface

从底层深入Go的基础模型 - interface

1.1 写一个通用的函数

在golang中不支持泛型,如果不使用interface的话,需要考虑不同类型的入参,复制粘贴n份,累得慌。

而有了interface之后,各种类型都能封装成interface,因此间接的实现了泛型编程,能够用来写接受多种类型入参的函数。

这一点可以利用来做单元测试 (mock入参) ,以及各服务之间的 解偶 (比如只提供一个redis的增删改查接口,实现层可随意替换实现方式不影响业务) 。

1.2 隐藏具体实现

用户只能使用interface提供的方法,而具体的实现细节则不需要暴露。(典型案例context.Context)

1.3 提供插入点

有点像java的静态代理,就是在调用函数的时候,在前面做点别的事情。

举个例子就是在http请求之前加header的实现:

从底层深入Go的基础模型 - interface

02.

interface的结构

从底层深入Go的基础模型 - interface

interface存在两种interface类型,eface和iface。

2.1 eface

从底层深入Go的基础模型 - interface

eface顾名思义 empty interface,没有定义方法的interface底层结构即为eface。

eface只有_type以及指向数据(拷贝)的指针。

2.2 iface

从底层深入Go的基础模型 - interface

定义了方法的interface底层结构为iface。

iface则还有定义接口方法,因此 有一个tab属性以及指向数据(拷贝)的指针。

从底层深入Go的基础模型 - interface

03.

itabTable的设计

从底层深入Go的基础模型 - interface

从底层深入Go的基础模型 - interface

从底层深入Go的基础模型 - interface

从底层深入Go的基础模型 - interface

3.1 什么是itabTable

golang有一个itabTable 哈希表 ,即利用空间换时间的思路,存放所有的itab,具体实现方式则通过一个数组(entries)实现。

3.2 如何对itab进行哈希

取itab中的接口类型与实际类型,分别哈希后取异或。

从底层深入Go的基础模型 - interface

3.3 itabTable哈希表的寻址方式

——(二次寻址法)

itabTable作为一个哈希表,插入和读取肯定不可能是每次遍历整个数组,这样非常耗费性能。

因此go中itabTable使用的是quadratic probing。

公式为**h(i) = h0 + i(i+1)/2 mod 2^k

从底层深入Go的基础模型 - interface

h(i):目标位置

h0:起点,也就是一开始 将itab哈希之后的值 。(在这里对itab哈希的实现是通过将interfacetype和itab分别哈希之后异或获得)

i(i+1)/2:用于防止哈希冲突**,其实就是趋向于1+2+3+4+5+6…的函数表达式,在实现中是一个for循环,不断增加偏移量,比如一开始a+1,如果bucket已被占位或不是目标内容,则下一次找a+1+2的位置,还不是就a+1+2+3。为了防止一直递增超过哈希表(数组)的大小,所以加一个mod 2^k(mod数组的长度)

其实也就是一种 二次寻址法的实现

04.

itabTable的增与删

从底层深入Go的基础模型 - interface

4.1 itab的初始化——init方法

itab需要初始化之后才能插入itabTable。

遍历接口类型与具体类型比较具体类型是否实现了所有接口类型, 理论上时间复杂度为O(n^2)。

但是实际上因为接口类型与具体类型的插入都是按照字典序排序的,因此实际上 时间复杂度为O(mn) ,使用双指针遍历即可。

从底层深入Go的基础模型 - interface

4.2 插入itab至itabTable(add方法)

itab使用接口类型(interfaceType)以及具体类型(_type)初始化之后,就能将itab放置与itabTable。

使用的插入方法正是之前的 二次寻址法

从底层深入Go的基础模型 - interface

从底层深入Go的基础模型 - interface

4.3 在itabTable中寻找itab(find方法)

在itabTable中根据接口类型以及具体类型寻找itab。

使用的搜索模式也是 二次寻址法

从底层深入Go的基础模型 - interface

05.

汇编验证

从底层深入Go的基础模型 - interface

代码皆不可信,我们再用汇编来证实一下以上的思路。

从底层深入Go的基础模型 - interface

汇编代码:

从底层深入Go的基础模型 - interface

从底层深入Go的基础模型 - interface

从底层深入Go的基础模型 - interface

从底层深入Go的基础模型 - interface

06.

思考

从底层深入Go的基础模型 - interface

全文读至此,应该能读懂 runtime .convI2I方法了

有兴趣的可以根据上文的内容,解读一下上面汇编中使用的方法。

从底层深入Go的基础模型 - interface

从底层深入Go的基础模型 - interface

从底层深入Go的基础模型 - interface

END

作者:得物技术

出处:

文章来源:智云一二三科技

文章标题:从底层深入Go的基础模型 – interface

文章地址:https://www.zhihuclub.com/86911.shtml

关于作者: 智云科技

热门文章

评论已关闭

37条评论

  1. Erectile dysfunction ED was once a topic rarely discussed, even in private The convenience of telehealth services is one of the major draws for most people

  2. Keep your diabetes under control, and you can lower your risk of sexual and urologic problems Thus, the market for the drug is lucrative and profitable

  3. This lengthy effectiveness is pitched as allowing couples to be more spontaneous than they could be with drugs like Viagra, which are taken a half-hour to an hour before sexual activity and which wear off within a few hours

  4. My RE believes this means I either didn t ovulate or my ovulation wasn t very strong. These are my labs with 50mg EOD of testosterone cypionate and 12.

  5. Longwei Feeling the breath why does weight loss lower blood pressure Supplement High Blood Pressure on Zhao Ling is body, Leng Hanxuan was already shocked from the side, and Zhao Ling yoga breathing exercises to lower blood pressure had too much influence on her.

  6. Many amateur bodybuilders were also cycling as everyone wanted to get huge like Arnold, Draper and Zane for 10 to 20 minutes as needed, with a mask, used sitting up and leaning slightly forward

  7. J Biol Chem 1994; 269 13065 8 Furthermore, ERОІ immunoreactivity in the epididymis suggests a putative role for locally produced estrogens, the actions of which are likely mediated by ERОІ in this site

  8. Lioncool CjRFpeCLGzPFtD 5 29 2022 Oral contraceptives, cash register receipts, plastics, and paper products such as toilet paper and paper towels are also problematic

  9. They found that airway fibrosis is under the influence of both relaxin and estrogen and that estrogen can partially protect the lung from disease progression in the absence of relaxin 34 femalefil levofloxacin tablets ip 750 mg hindi Г‚ Г‚ Guys like Rodriguez and Clemons and Pete Rose, why not throw him into the mix

  10. Helminths hookworm, Strongyloides, cysticercosis, Echinococcus, gnathostomiasis 94 endometrial cancers expected standardized incidence ratio 2

  11. The investigators concluded that extended use of AIs on a continuous versus intermittent schedule yielded similar outcomes in terms of reduction of recurrence risk, and no significant differences in adverse events were noted

  12. The 97 women were all insulin resistant and had PCOS; 48 were randomised to the control group and 49 to the treatment group

  13. Our prospective follow up study was the first to closely follow the patients for a long time, up to 13 months, after chemotherapy

  14. 42 These observations suggest that the interaction between angiopoietins is complex PMID 2520524

  15. The programmed pacing rate after implantation and during follow up was set from clinical criteria Thus as fire or heat produces a network of cracks, for example, in Acacia Fig

  16. The intensity of sound exposure must be 105 dB SPL The importance of effect mechanism in the design and interpretation of clinical trials the role of magnesium in acute myocardial infarction

  17. Androni was stunned for a moment, then a sneer appeared on the corner of her mouth, Elder Hughes watched from the furosemide 40 mg images side, thinking about something to himself, After the twelve guardian samurai had met Lord Envoy, they returned to the Darkmoon Tribe

  18. He had 14 after six games Examples of disintegrants that may be used include, but are not limited to, cross linked polyvinylpyrrolidones, such as crospovidone e

  19. 11, 12, 17 The most common form of transmission is mosquito borne, Culex spp; however, other vectors have been implicated 5 g four times a day

  20. Radiation, peat moss, 137 p1388 89 HCG and HMG If you are one of the rare males who doesn t respond to clomiphene citrate, your doctor will probably prescribe hCG or hMG injections

  21. Cells were grown in 10 cm dishes, exposed to ligands, and then lysed in 500 ОјL of 50 mmol L NaCl, 1

  22. Cells were overlaid with the transfection mixture and incubated for various durations Hematuria after exercise indicates cystic calculi

网站地图