構造体と同じく、インターフェイスも別のインターフェイスに埋め込むことができる。
下の例では、BazI に FooI と BarI を埋め込んでいる。すると、BazI を実装した構造体 Baz では、FooI と BarI のメソッドを、あたかも自分のメソッドのように使えるようになる。
package main
import "fmt"
type Foo struct {
a int
}
type FooI interface {
getA() int
}
func (p *Foo) getA() int {
return p.a
}
type Bar struct {
b int
}
type BarI interface {
getB() int
}
func (p *Bar) getB() int {
return p.b
}
type Baz struct {
Foo
Bar
}
type BazI interface {
FooI
BarI
}
func main() {
a := []FooI{
&Foo{1},
&Foo{2},
&Baz{},
}
b := []BarI{
&Bar{10},
&Bar{20},
&Baz{},
}
c := []BazI{
&Baz{},
&Baz{Foo{1}, Bar{2}},
&Baz{Foo{3}, Bar{4}},
}
for i := 0; i < 3; i++ {
fmt.Println(a[i].getA())
fmt.Println(b[i].getB())
fmt.Println(c[i].getA())
fmt.Println(c[i].getB())
}
}
^o^ > go run interface_embed.go 1 10 0 0 2 20 1 2 0 0 3 4