接口

iface和eface区别

结构体区别

type iface struct {
tab  *itab
data unsafe.Pointer
}

type ITab struct {
Inter *InterfaceType //接口类型
Type  *Type //实体类型
Hash  uint32     // copy of Type.Hash. Used for type switches.
Fun   [1]uintptr // variable sized. fun[0]==0 means Type does not implement Inter.
}

type InterfaceType struct {
Type  //接口类型元数据
PkgPath Name      // import path
Methods []Imethod // sorted by hash //接口方法
}

type eface struct {
_type *_type //实体类型
data  unsafe.Pointer
}

Go 语言各种数据类型都是在 _type 字段的基础上,增加一些额外的字段来进行管理的

type arraytype struct {
typ _type
elem *_type
slice *_type
len uintptr
}
type chantype struct {
typ _type
elem *_type
dir uintptr
}
type slicetype struct {
typ _type
elem *_type
}
type structtype struct {
typ _type
pkgPath name
fields []structfield 
}

实现了接收者是值类型的方法,相当于自动实现了接收者是指针类型的方法;而实 现了接收者是指针类型的方法,不会自动生成对应接收者是值类型的方法

如何选择

使用指针作为方法的接收者的理由如下: 1)方法能够修改接收者指向的值。 2)避免在每次调用方法时复制该值,在值的类型为大型结构体时,这样做会更加高效。

如果类型具备“原始的本质”,也就是说它的成员都是由 Go 语言里内置的原始类型,如字符 串、整型值等构成,那就定义值接收者类型的方法。像内置的引用类型,如 slice、map、 interface、channel,这些类型比较特殊,声明它们的时候,实际上是创建了一个 header,对于它们 也是直接定义值接收者类型的方法。这样,调用函数时,是直接复制了这些类型的 header,而 header 本身就是为复制设计的。这种也应该是声明值接收者类型的方法。

断言原理

results matching ""

    No results matching ""