方法接收器
Go语言中的方法(Method)
是一种作用于特定类型变量的函数。这种特定类型变量叫做接收者(Receiver)
。
方法的定义格式如下:
func (接收者变量 接收者类型) 方法名(参数列表) (返回参数) {
函数体
}
其中,
-
接收者变量:接收者中的参数变量名在命名时,官方建议使用接收者类型名称首字母的小写,而不是
self
、this
之类的命名。例如,Person
类型的接收者变量应该命名为p
,Connector
类型的接收者变量应该命名为c
等。 -
接收者类型:接收者类型和参数类似,可以是指针类型和非指针类型。
-
方法名、参数列表、返回参数:具体格式与函数定义相同。
package main
import "fmt"
type Player struct {
Name string
HealthPoint int
Level int
NowPosition []int
Prop []string
}
func NewPlayer(name string, hp int, level int, np []int, prop []string) *Player {
return &Player{
name,
hp,
level,
np,
prop,
}
}
func (p Player) attack() {
fmt.Printf("%s发起攻击!\n", p.Name)
}
func (p *Player) attacked() {
fmt.Printf("%s被攻击!\n", p.Name)
p.HealthPoint -= 10
fmt.Println(p.HealthPoint)
}
func (p *Player) buyProp(prop string) {
p.Prop = append(p.Prop, prop)
fmt.Printf("%s购买道具!\n", p.Name)
}
func main() {
player := NewPlayer("yuan", 100, 100, nil, nil)
player.attack()
player.attacked()
fmt.Println(player.HealthPoint)
player.buyProp("魔法石")
fmt.Println(player.Prop)
}
提示
1、官方定义:Methods are not mixed with the data definition (the structs): they are orthogonal to types; representation(data) and behavior (methods) are independent
提示
2、方法与函数的区别是,函数不属于任何类型,方法属于特定的类型。