Meaning of a struct with embedded anonymous interface?

后端 未结 5 1670
感动是毒
感动是毒 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 08:53

    I will give my explanation too. The sort package defines an unexported type reverse, which is a struct, that embeds Interface.

    type reverse struct {
        // This embedded Interface permits Reverse to use the methods of
        // another Interface implementation.
        Interface
    }
    

    This permits Reverse to use the methods of another Interface implementation. This is the so called composition, which is a powerful feature of Go.

    The Less method for reverse calls the Less method of the embedded Interface value, but with the indices flipped, reversing the order of the sort results.

    // Less returns the opposite of the embedded implementation's Less method.
    func (r reverse) Less(i, j int) bool {
        return r.Interface.Less(j, i)
    }
    

    Len and Swap the other two methods of reverse, are implicitly provided by the original Interface value because it is an embedded field. The exported Reverse function returns an instance of the reverse type that contains the original Interface value.

    // Reverse returns the reverse order for data.
    func Reverse(data Interface) Interface {
        return &reverse{data}
    }
    

提交回复
热议问题