Go语言中的 方法(method) 是一种作用于特定类型变量的函数。这种特定类型的变量叫做 接受者(Receiver)。方法的定义格式如下:

    1. func (接受者变量 接受者类型) 方法名(参数列表) (返回参数){
    2. 函数体
    3. }

    其中:

    • 接收者变量:接收者中的参数变量在命名时,官方建议使用接收者类型名称首字母小写,而不是self,this之类的命名。例如,Person类型的接收者变量应该命名为p,Connector 类型的接收者变量应该命名为 c 等。
    • 接收者类型:接收者类型和参数类型,可以是指针类型和非指针类型。
    • 方法名、参数列表、返回参数:具体格式与函数定义相同。
    1. package main
    2. import "fmt"
    3. type Player struct {
    4. Name string
    5. HealthPoint int
    6. Magic int
    7. }
    8. // 方法结构体构造函数
    9. func NewPlayer(name string, hp int, mp int) *Player {
    10. return &Player{ // 跟返不返回指针类型没关系,但是在函数调用的时候有关系
    11. Name: name,
    12. HealthPoint: hp,
    13. Magic: mp,
    14. }
    15. }
    16. func (p Player) attack() {
    17. fmt.Printf("%s发起攻击\n", p.Name)
    18. }
    19. // 指针接收器,接收的是地址
    20. func (p *Player) attacked() {
    21. fmt.Printf("%s受到攻击\n", p.Name)
    22. p.HealthPoint -= 1
    23. fmt.Println(p.HealthPoint)
    24. }
    25. // 普通接收器,接收的值拷贝
    26. func (p Player) BuyProp() {
    27. fmt.Printf("%s购买道具!\n", p.Name)
    28. }
    29. func main() {
    30. play := NewPlayer("sbh", 100, 200)
    31. //fmt.Printf("%p", play)
    32. play.attack() // 做了语法糖把play.attack() 转换成了 (*play).attack()
    33. play.attacked()
    34. fmt.Println(play.HealthPoint)
    35. play.BuyProp()
    36. }

    1、官方定义:Methods are not mixed with the data definition (the structs): they are orthogonal to types; representation(data) and behavior (methods) are independent 2、方法与函数的区别是,函数不属于任何类型,方法属于特定的类型。