普通情况下,类型 T 和 指针T 上的方法集是互相继承的,即接收器是T和*T时,方法都可以调用成功.
type Cat struct{
}
func (c *Cat) Test() { //这里接收器是指针 func (c Cat) Test() 不是指针,也没问题
fmt.Println("test)
}
func main() {
c := Cat{ } //无论T和指针T都能调用方法
c.Test()
b:=&Cat{}
b.Test()
}
but:
在接口中的method,对于普通类型T:
T的方法集里不会继承包含指针T实现的method,除非T自己实现相对应的method。
但是,指针T会继承T的方法集。
type test interface {
Test()
}
type User struct {
Name string
Age int
}
func (u *User) Test() { //接收器为指针
fmt.Println("name is: ", u.Name)
}
func tester(u test) {
u.Test()
}
func main() {
u := User{"tt", 12}
u.Test()
tester(&u) //这里必须传入指针才是对的,因为接收器为指针*T,T不会继承*T的方法
}
type test interface {
Test()
}
type User struct {
Name string
Age int
}
func (u User) Test() { //接收器为值
fmt.Println("name is: ", u.Name)
}
func tester(u test) {
u.Test()
}
func main() {
u := User{"tt", 12}
u.Test()
tester(&u) //这里传入值和指针都是可以的,因为*T可以继承T的方法集,所以实现了T的方法即实现了*T的方法,*T也可以调用方法
tester(u) //这里传入值和指针都是可以的,因为*T可以继承T的方法集,所以实现了T的方法即实现了*T的方法,*T也可以调用方法
}