<aside> 💡 Golang 方法总是绑定对象实例,并隐式将实例作为第一实参 (receiver)。

</aside>

<aside> 💡 注意传参的方式:值传递还是引用传递,为了提高效率,一般使用指针类型

</aside>

• 只能为当前包内命名类型定义方法。
• 参数 receiver 可任意命名。如方法中未曾使用 ,可省略参数名。
• 参数 receiver 类型可以是 T 或 *T。基类型 T 不能是接口或指针。 
• 不支持方法重载,receiver 只是参数签名的组成部分。
• 可用实例 value 或 pointer 调用全部方法,编译器自动转换。

方法的定义

  func (recevier type) methodName(参数列表)(返回值列表){}

  参数和返回值可以省略
package main

type Test struct{}

// 无参数、无返回值
func (t Test) method0() {

}

// 单参数、无返回值
func (t Test) method1(i int) {

}

// 多参数、无返回值
func (t Test) method2(x, y int) {

}

// 无参数、单返回值
func (t Test) method3() (i int) {
    return
}

// 多参数、多返回值
func (t Test) method4(x, y int) (z int, err error) {
    return
}

// 无参数、无返回值
func (t *Test) method5() {

}

// 单参数、无返回值
func (t *Test) method6(i int) {

}

// 多参数、无返回值
func (t *Test) method7(x, y int) {

}

// 无参数、单返回值
func (t *Test) method8() (i int) {
    return
}

// 多参数、多返回值
func (t *Test) method9(x, y int) (z int, err error) {
    return
}

func main() {}

实例

普通函数与方法的区别

  1. 对于普通函数,接收者为值类型时,不能将指针类型的数据直接传递,反之亦然。
  2. 对于方法(如struct的方法),接收者为值类型时,可以直接用指针类型的变量调用方法,反过来同样也可以。

实例

匿名字段

Golang匿名字段 :可以像字段成员那样访问匿名字段方法,编译器负责查找。