メソッドの継承とかオーバーライド(っぽい事)
ケース:
3rd party ライブラリの実装を利用しつつも一部のメソッドだけ書き換えたい。
具体的には、Aというインターフェースを実装したAImplのメソッドをオーバーライドしたい。
こういう場合は、AImplを匿名フィールド(埋め込みフィールド)として持つBImplを作ってやれば、AImplを継承しつつメソッドをオーバーライドする(かのような)事ができる。
(↓)こんな感じで。
http://play.golang.org/p/9EjYiAj3YQ
package main import "fmt" type A interface { Hoge() string } type AImpl struct { value string } func (self AImpl) Hoge() string { return "This is generated in AImpl.Hoge(), value is " + self.value } type BImpl struct { AImpl } func (self BImpl) Hoge() string { original := self.AImpl.Hoge() overwritten := original + " ; This is added in B.Hoge(), value is " + self.value + "!" return overwritten } func main() { var a A a = BImpl{AImpl{"yeah"}} fmt.Println(a.Hoge()) }
出力:This is generated in AImpl.Hoge(), value is yeah ; This is added in B.Hoge(), value is yeah!