メニュー

2013年1月30日

Go言語でstructにinterfaceを埋め込み

structにinterfaceを埋め込み出来た。
外部モジュールから受け取ったinterfaceをラップして拡張したいときに使えそう。

type Foo interface {
    Print()
}

type MyFoo struct {}

func (f *MyFoo) Print() {
    fmt.Println("MyFoo")
}

type Bar struct {
    Foo
}

func main() {
    var f MyFoo
    
    b := Bar{&f}
    b.Print()
    
    b2 := Bar{}
    b2.Foo = &f
    b.Print()
}

0 件のコメント:

コメントを投稿