Meaning of a struct with embedded anonymous interface?

后端 未结 5 1669
感动是毒
感动是毒 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:07

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

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

    Notice how here it swaps (j,i) instead of (i,j) and also this is the only method declared for the struct reverse even if reverse implement sort.Interface

    // 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)
    }
    

    Whatever struct is passed inside this method we convert it to a new reverse struct.

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

    The real value comes if you think what would you have to do if this approach was not possible.

    1. Add another Reverse method to the sort.Interface ?
    2. Create another ReverseInterface ?
    3. ... ?

    Any of this change would require many many more lines of code across thousands of packages that want to use the standard reverse functionality.

提交回复
热议问题