方法接收者(Receiver),顾名思义就是谁接收了这个方法。
概念
在Golang中,没有类(Class),但是可以用结构体(Struct)实现面向对象编程思想。
type Student struct {
name string
age int
}
注意区分函数和方法,函数是没有方法接收者的,而方法有方法接收者。
// 函数
func Say() {
...
}
// 方法
func (s Student) Say() {
...
}
Receiver是某一个特定的Struct类型,当你将函数Function附加到该Receiver, 意味着这个方法Method被该Receiver接收了,该方法就能获取该Receiver的属性和其他方法。
func (s Student) Say() {
// 获取年龄属性
fmt.Printf("年龄:%d", &s.age)
}
类型
1.值接收者
当方法为值接收者时,该方法内所获取的属性值皆为副本,也就是说方法内再怎么改变,也只限方法内,并不会改变调用者。
type Student struct {
name string
age int
}
func (s Student) say() {
s.age = s.age + 1
fmt.Println("say:", s.age)
}
func main() {
s := Student{name: "zhangsan", age: 20}
s.say()
fmt.Println("s:", s.age)
}
返回结果:
say: 21
s: 20
2.指针接收者
当方法为指针接收者时,该方法内所获取的属性值皆为指针类型,修改其属性,会直接影响调用者。
type Student struct {
name string
age int
}
func (s *Student) say() {
s.age = s.age + 1
fmt.Println("say:", s.age)
}
func main() {
s := Student{name: "zhangsan", age: 20}
s.say()
fmt.Println("s:", s.age)
}
返回结果:
say: 21
s: 21