1、接口、接收者调用者、值类型指针类型
Demo 1
当接收者为值类型时,无论调用者是值类型还是指针类型,接收者的更改都不会影响调用者。
当接收者是指针类型时,无论调用者是值类型还是指针类型,接收者的更改均会影响调用者。
type Person struct {
Name string
Age int
}
func (p Person) GetName() string {
return p.Name
}
func (p Person) SetName(name string) {
p.Name = name
}
func (p *Person) GetAge() int {
return p.Age
}
func (p *Person) SetAge(age int) {
p.Age = age
}
func TestF(test *testing.T) {
Luffy := Person{
Name: "luffy",
Age: 21,
}
Sanji := &Person{
Name: "sanji",
Age: 23,
}
fmt.Printf("My name is %s, I'm %d years old \n", Luffy.Name, Luffy.Age)
fmt.Printf("My name is %s, I'm %d years old \n", Sanji.Name, Sanji.Age)
fmt.Println(".................3 years later ......................")
Luffy.SetName("luffy3")
Luffy.SetAge(Luffy.Age + 3)
Sanji.SetName("sanji3")
Sanji.SetAge(Sanji.Age + 3)
fmt.Printf("My name is %s, I'm %d years old \n", Luffy.GetName(), Luffy.GetAge())
fmt.Printf("My name is %s, I'm %d years old \n", Sanji.GetName(), Sanji.GetAge())
}
打印结果
My name is luffy, I'm 21 years old
My name is sanji, I'm 23 years old
.................3 years later ......................
My name is luffy, I'm 24 years old
My name is sanji, I'm 26 years old
总结:
Demo2
type PersonInterface interface {
SayHi()
}
type Man struct {}
type Woman struct {}
func (m Man) SayHi() {
fmt.Println("I'm a man")
}
func (w *Woman) SayHi() {
fmt.Println("I'm a woman")
}
func TestF(test *testing.T) {
var man PersonInterface = Man{}
man.SayHi()
var ptrMan PersonInterface = &Man{}
ptrMan.SayHi()
var woman PersonInterface = Woman{} //这里报错,错误提示见下面贴图
woman.SayHi()
var ptrWoman PersonInterface = &Woman{}
ptrWoman.SayHi()
}
总结:实现了接收者是值类型的方法,相当于自动实现了接收者是指针类型的方法;而实现了接收者是指针类型的方法,不会自动生成对应接收者是值类型的方法。【https://qcrao91.gitbook.io/go/interface/zhi-jie-shou-zhe-he-zhi-zhen-jie-shou-zhe-de-qu-bie】
推荐阅读:https://www.infoq.cn/article/wDURRBz1Nv3IbIeviIJF