为什么如此设计?

Meaning of a struct with embedded anonymous interface?
摘录其中比较关键的解释如下:

  1. In this way reverse implements the sort.Interface and we can override a specific method without having to define all the others.

  2. 结构体创建时,可以使用任何实现了Interface的obj来初始化,参考:
    1. package main
    2. import "fmt"
    3. // some interface
    4. type Stringer interface {
    5. String() string
    6. }
    7. // a struct that implements Stringer interface
    8. type Struct1 struct {
    9. field1 string
    10. }
    11. func (s Struct1) String() string {
    12. return s.field1
    13. }
    14. // another struct that implements Stringer interface, but has a different set of fields
    15. type Struct2 struct {
    16. field1 []string
    17. dummy bool
    18. }
    19. func (s Struct2) String() string {
    20. return fmt.Sprintf("%v, %v", s.field1, s.dummy)
    21. }
    22. // container that can embedd any struct which implements Stringer interface
    23. type StringerContainer struct {
    24. Stringer
    25. }
    26. func main() {
    27. // the following prints: This is Struct1
    28. fmt.Println(StringerContainer{Struct1{"This is Struct1"}})
    29. // the following prints: [This is Struct1], true
    30. fmt.Println(StringerContainer{Struct2{[]string{"This", "is", "Struct1"}, true}})
    31. // the following does not compile:
    32. // cannot use "This is a type that does not implement Stringer" (type string)
    33. // as type Stringer in field value:
    34. // string does not implement Stringer (missing String method)
    35. fmt.Println(StringerContainer{"This is a type that does not implement Stringer"})
    36. }

golang 结构体中的匿名接口