方法集

golang类型有一个与之相关的方法集,这决定了它是否实现某个接口
  • 类型T方法集包含所有reciver T方法
  • 类型*T方法集包含所有receiver T+*T方法
  • 匿名嵌入S,则T方法集包含所有receiver S方法
  • 匿名嵌入*S,则T方法集包含所有receiver S+*S方法
  • 匿名嵌入S或*S,则*T方法集包含所有receiver S+*S方法

 

package main

import "fmt"

type tester interface {
        tVal()
        tPtr()
}

type T2 struct {
        *S
}

type T1 struct {
        S
}

type S struct {
}

func (p *S) tPtr() { fmt.Printf("caller's type is: %#T\n", p) }

func (v S) tVal() { fmt.Printf("caller's type is: %#T\n", v) }

func main() {
        var t tester

        s := S{}

        //type S include method tVal(receiver S) but not tPtr(receiver *S)
        //t = s

        //type *S include method tVal and tPtr
        t = &s
        t.tPtr()
        t.tVal()

        //type T1 with annonymous S embedded, include method tVal but not tPtr
        //d := T1{S{}}
        //t = d

        //type T2 with annonymous *S embedded, include method tVal and tPtr
        d1 := T2{&S{}}
        t = d1
        t.tPtr()
        t.tVal()

        //type *T1 with annonymous S embedded, include method tVal and tPtr
        d2 := &T1{S{}}
        t = d2
        t.tPtr()
        t.tVal()

        //type *T2 with annonymous *S embedded, include method tVal and tPtr
        d3 := &T2{&S{}}
        t = d3
        t.tPtr()
        t.tVal()
}

  

转载于:https://www.cnblogs.com/adba/p/8337112.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值