Go语言中的 方法(method) 是一种作用于特定类型变量的函数。这种特定类型的变量叫做 接受者(Receiver)。方法的定义格式如下:
func (接受者变量 接受者类型) 方法名(参数列表) (返回参数){
函数体
}
其中:
- 接收者变量:接收者中的参数变量在命名时,官方建议使用接收者类型名称首字母小写,而不是self,this之类的命名。例如,Person类型的接收者变量应该命名为p,Connector 类型的接收者变量应该命名为 c 等。
- 接收者类型:接收者类型和参数类型,可以是指针类型和非指针类型。
- 方法名、参数列表、返回参数:具体格式与函数定义相同。
package main
import "fmt"
type Player struct {
Name string
HealthPoint int
Magic int
}
// 方法结构体构造函数
func NewPlayer(name string, hp int, mp int) *Player {
return &Player{ // 跟返不返回指针类型没关系,但是在函数调用的时候有关系
Name: name,
HealthPoint: hp,
Magic: mp,
}
}
func (p Player) attack() {
fmt.Printf("%s发起攻击\n", p.Name)
}
// 指针接收器,接收的是地址
func (p *Player) attacked() {
fmt.Printf("%s受到攻击\n", p.Name)
p.HealthPoint -= 1
fmt.Println(p.HealthPoint)
}
// 普通接收器,接收的值拷贝
func (p Player) BuyProp() {
fmt.Printf("%s购买道具!\n", p.Name)
}
func main() {
play := NewPlayer("sbh", 100, 200)
//fmt.Printf("%p", play)
play.attack() // 做了语法糖把play.attack() 转换成了 (*play).attack()
play.attacked()
fmt.Println(play.HealthPoint)
play.BuyProp()
}
1、官方定义:Methods are not mixed with the data definition (the structs): they are orthogonal to types; representation(data) and behavior (methods) are independent 2、方法与函数的区别是,函数不属于任何类型,方法属于特定的类型。