通过receiver实现(函数名前面加结构体定义表示receiver, 表明该函数是这个receiver的一个方法,如:func (a A) Print())
不同结构体的方法之间可以重名。
receiver可以是值传递也可以是指针传递((a A)或者(a *A))。
type A struct{
name string}type B struct{
name string}func(a *A)Print(){
fmt.Println("My name is", a.name)}func(b B)Print(){
fmt.Println("My name is", b.name)}funcmain(){
a := A{"He"}
a.Print()
b := B{"She"}
b.Print()}
类型别名和方法的组合
方法绑定可以使用在类型别名上
方法绑定只能绑定当前包下的函数与结构体或类型别名
type MyInt intfunc(a MyInt)Print(){
fmt.Println("This is MyInt")}funcmain(){var a MyInt
a.Print()}
Method Value vs. Method Expression
Method Value:通过变量调用方法 a.Print()。
Method Expression:通过类型调用方法 (*MyInt).Print(&a)。
类型,方法名 ,其中要把该类型的变量作为第一个参数传进去,方法的其他参数位置顺延。
type MyInt intfunc(a MyInt)Print(t int){
fmt.Println("This is MyInt", t)}funcmain(){var a MyInt
a.Print(1)(*MyInt).Print(&a,1)}
方法method方法method通过receiver实现(函数名前面加结构体定义表示receiver, 表明该函数是这个receiver的一个方法,如:func (a A) Print())不同结构体的方法之间可以重名。receiver可以是值传递也可以是指针传递((a A)或者(a *A))。type A struct { name string}type B stru...