方法集

方法集规定了方法的接收规则。

从值的角度,也就是被调用的方法里面参数的角度来说:

  • 值的方法集,只包含接收者是值的情况;
  • 指针的方法集,包含接收者是值和接收者是指针的情况;

从接收者角度:

  • 如果方法绑定在值上面,那么方法中的参数为值,或者为指针,都可以使用;
  • 如果方法绑定在指针上面,那么方法中的参数为指针时才可以使用。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
type notifier interface{
notify()
}
type user struct{
name string
email string
}

func (u *user) notify(){
dosomething()
}
//调用do方法,那么上面这种绑定指针的方式,不能使用,只能使用下面的方式;
func do(n notifier){
n.notify()
}
func (u user) notify(){
dosomething()
}