1. 程式人生 > >方法集

方法集

var pack func ola truct all clas inter package

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

  

方法集