import (
"fmt"
"reflect"
"testing"
)
type Person struct {
name string
age int
}
func (this *Person) walk() {
fmt.Printf("%s is walking\n", this.name)
}
func (this Person) sing() {
fmt.Printf("%s is singing\n", this.name)
}
func TestMethodReceiver(t *testing.T) {
p := Person{
name: "xiaoming",
age: 20,
}
p.walk()
p.sing()
x := &p
x.walk()
x.sing()
fmt.Println(reflect.TypeOf(p).Kind(), reflect.TypeOf(x).Kind())
}
=== RUN TestMethodReceiver
ptr
xiaoming is walking
struct
xiaoming is singing
ptr
xiaoming is walking
struct
xiaoming is singing
struct ptr
--- PASS: TestMethodReceiver (0.00s)
PASS
测试版本: golang>=1.18.2
结论:无论方法的接收者是指针对象还是值对象,指针对象和方法对象均可以调用此方法。 也就是说,只要你的自定义类型实现了方法,不管方法的接收对象是指针类型还是值类型,也不管调用者是值类型还是指针类型,方法都可以被调用。
关于这个话题,好多人都是说方法接收者是指针对象时,指针对象和方法对象都可以调用。但是官方说法刚好相反。实践出真知