Meaning of a struct with embedded anonymous interface?

后端 未结 5 1656
感动是毒
感动是毒 2020-12-07 08:42

sort package:

type Interface interface {
    Len() int
    Less(i, j int) bool
    Swap(i, j int)
}

...

type reverse struct {
    Interface
}
         


        
5条回答
  •  既然无缘
    2020-12-07 09:06

    The statement

    type reverse struct {
        Interface
    }
    

    enables you to initialize reverse with everything that implements the interface Interface. Example:

    &reverse{sort.Intslice([]int{1,2,3})}
    

    This way, all methods implemented by the embedded Interface value get populated to the outside while you are still able to override some of them in reverse, for example Less to reverse the sorting.

    This is what actually happens when you use sort.Reverse. You can read about embedding in the struct section of the spec.

提交回复
热议问题