lyd2004888 发表于 2018-9-20 06:54:49

golang的interface剖析

92   // both inter and typ have method sorted by name,  93   // and interface names are unique,
  94   // so can iterate over both in lock step;
  95   // the loop is O(ni+nt) not O(ni*nt).       // 按name排序过的,因此这里的匹配只需要O(ni+nt)
  99   j := 0
  
100   for k := 0; k < ni; k++ {
  
101         i := &inter.mhdr
  
102         itype := inter.typ.typeOff(i.ityp)
  
103         name := inter.typ.nameOff(i.name)
  
104         iname := name.name()
  
109         for ; j < nt; j++ {
  
110             t := &xmhdr
  
111             tname := typ.nameOff(t.name)
  
112             if typ.typeOff(t.mtyp) == itype && tname.name() == iname {
  
118                     if m != nil {
  
119                         ifn := typ.textOff(t.ifn)
  
120                         *(*unsafe.Pointer)(add(unsafe.Pointer(&m.fun), uintptr(k)*sys.PtrSize)) = ifn // 找到匹配,将实际类型的方法填入itab的fun
  
121                     }
  
122                     goto nextimethod
  
123               }
  
124             }
  
125         }
  
135   nextimethod:
  
136   }
  
140   h := itabhash(inter, typ)             //插入上面的全局hash
  
141   m.link = hash
  
142   atomicstorep(unsafe.Pointer(&hash), unsafe.Pointer(m))
  
143 }
  



页: [1]
查看完整版本: golang的interface剖析