为什么如此设计?
Meaning of a struct with embedded anonymous interface?
摘录其中比较关键的解释如下:
- In this way
reverseimplements thesort.Interfaceand we can override a specific method without having to define all the others. - 结构体创建时,可以使用任何实现了
Interface的obj来初始化,参考:package mainimport "fmt"// some interfacetype Stringer interface {String() string}// a struct that implements Stringer interfacetype Struct1 struct {field1 string}func (s Struct1) String() string {return s.field1}// another struct that implements Stringer interface, but has a different set of fieldstype Struct2 struct {field1 []stringdummy bool}func (s Struct2) String() string {return fmt.Sprintf("%v, %v", s.field1, s.dummy)}// container that can embedd any struct which implements Stringer interfacetype StringerContainer struct {Stringer}func main() {// the following prints: This is Struct1fmt.Println(StringerContainer{Struct1{"This is Struct1"}})// the following prints: [This is Struct1], truefmt.Println(StringerContainer{Struct2{[]string{"This", "is", "Struct1"}, true}})// the following does not compile:// cannot use "This is a type that does not implement Stringer" (type string)// as type Stringer in field value:// string does not implement Stringer (missing String method)fmt.Println(StringerContainer{"This is a type that does not implement Stringer"})}
