码迷,mamicode.com
首页 > 其他好文 > 详细

方法集

时间:2018-01-23 20:18:57      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:fun   log   pre   包含   print   gpo   include   caller   决定   

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()
}

  

方法集

标签:fun   log   pre   包含   print   gpo   include   caller   决定   

原文地址:https://www.cnblogs.com/adba/p/8337112.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!