Meaning of a struct with embedded anonymous interface?

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.

Leave a Comment