golang类型有一个与之相关的方法集,这决定了它是否实现某个接口
- 类型T方法集包含所有reciver T方法
- 类型*T方法集包含所有receiver T+*T方法
- 匿名嵌入S,则T方法集包含所有receiver S方法
- 匿名嵌入*S,则T方法集包含所有receiver S+*S方法
- 匿名嵌入S或*S,则*T方法集包含所有receiver S+*S方法
package main import "fmt" type tester interface { tVal() tPtr() } type T2 struct { *S } type T1 struct { S } type S struct { } func (p *S) tPtr() { fmt.Printf("caller‘s type is: %#T\n", p) } func (v S) tVal() { fmt.Printf("caller‘s type is: %#T\n", v) } func main() { var t tester s := S{} //type S include method tVal(receiver S) but not tPtr(receiver *S) //t = s //type *S include method tVal and tPtr t = &s t.tPtr() t.tVal() //type T1 with annonymous S embedded, include method tVal but not tPtr //d := T1{S{}} //t = d //type T2 with annonymous *S embedded, include method tVal and tPtr d1 := T2{&S{}} t = d1 t.tPtr() t.tVal() //type *T1 with annonymous S embedded, include method tVal and tPtr d2 := &T1{S{}} t = d2 t.tPtr() t.tVal() //type *T2 with annonymous *S embedded, include method tVal and tPtr d3 := &T2{&S{}} t = d3 t.tPtr() t.tVal() }