[GO]方法集

指针变量的方法集

package main

import "fmt"

type Person struct {
    name string
    sex byte
    age int
}

func (p Person) SetValueInfoValue()  {
    fmt.Println("SetValueInfoValue")
}

func (p *Person) SetValueInfoPointer()  {
    fmt.Println("SetValueInfoPointer")
}

func main() {
    //结构体变量是一个指针变量,它能够调用哪些方法,这些方法就是一个集合,简称方法
    p := &Person{"mike", 'm', 18} //这里的就是一个指针类型了
    p.SetValueInfoValue() //func (p *Person) SetValueInfoPointer(),但其实它也可以使用下面的方式调用
    (*p).SetValueInfoPointer() //这里其实在内部,把(*p)转换成p后再调用,等价于上面
    //内部做的转换,先把指针p,转换成*p再调用
    (*p).SetValueInfoPointer()
    p.SetValueInfoValue()
    //用实例value和pointer调用方法(含匿名突)不受方法集约束,编译器问题查找全部方法,并自动转换receiver实参
    p.SetValueInfoPointer()
}

执行结果

SetValueInfoValue
SetValueInfoPointer
SetValueInfoPointer
SetValueInfoValue
SetValueInfoPointer

普通变量的方法集

package main

import "fmt"

type Person struct {
    name string
    sex byte
    age int
}

func (p Person) SetValueInfoValue()  {
    fmt.Println("SetValueInfoValue")
}

func (p *Person) SetValueInfoPointer()  {
    fmt.Println("SetValueInfoPointer")
}

func main() {
    p := Person{"mike", 'm', 18}
    p.SetValueInfoPointer() //这里方法需要的其实是一个指针类型,但这里依然可以编译通过,在内部,先反p转换为&p再调用,
}

猜你喜欢

转载自www.cnblogs.com/baylorqu/p/9631935.html
今日推荐