一個指向自定義類型的值的指針,它的方法集由該類型定義的所有方法組成,無論這些方法接受的是一個值還是一個指針。如果在指針上調用一個接受值的方法,Go語言會聰明地將該指針解引用,并將指針所指的底層值作為方法的接收者
~~~
package main
import "fmt"
type Student struct {
name string
age int
}
// 指針作為接收者 引用語義
func (s *Student) SetStuPointer() {
(*s).name = "Bob"
s.age = 18
}
// 值作為接收者 值語義
func (s Student) SetStuValue() {
s.name = "Peter"
s.age = 18
}
func main() {
//指針作為接收者,引用語義
s1 := &Student{"Miller", 18} //初始化
s1 .SetStuPointer()
s1.SetStuValue()
(*s1).SetStuValue()
fmt.Println(s1) // &{Bob 18}
}
~~~