go-pointer
要点
在访问
filed
时,pointer to struct
会自动解引用1
2
3
4
5type person struct {
name string
}
p := &person{"a"}
p.name // <=> (*p).name在调用
method
时,struct
(reciver
)会自动转换(取地址,解引用)1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21type Dog struct {
name string
}
func (d Dog) Bite(target string) {
fmt.Printf("%v bite %v\n", d.name, target)
}
func (d *Dog) Drink(target string) {
fmt.Printf("%v drink %v\n", d.name, target)
}
func main() {
a := Dog{"a"}
b := &Dog{"b"}
a.Bite("b")
b.Bite("a") // <=> (*b).Bite("a")
a.Drink("water") // <=> (&a).Drink("water")
b.Drink("beer") //
}function
参数不会转换