I'm looking at the sort.Reverse
code:
type reverse struct {
// This embedded Interface permits Reverse to use the methods of
// another Interface implementation.
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)
}
// Reverse returns the reverse order for data.
func Reverse(data Interface) Interface {
return &reverse{data}
}
As far as I understand reverse
implements Interface
(and overrides Less
) and *reverse
does not implement Interface
. Why does Reverse
return *reverse
(which somehow is Interface
)?
For your comment:
As far as I understand reverse implements Interface (and overrides Less)
There is no method overriding in Golang. It is not overriding Less
. It is implementing Less
of Interface
which is an interface
type:
type Interface interface {
// Len is the number of elements in the collection.
Len() int
// Less reports whether the element with
// index i should sort before the element with index j.
Less(i, j int) bool
// Swap swaps the elements with indexes i and j.
Swap(i, j int)
}
For the question asked:
Why does Reverse return *reverse (which somehow is Interface)
Because to change the order of the data it should be an address of the reverse struct. That's why it is *reverse
. Now you can pass any type implementing Interface
interface. And for implementing the Interface
you should implement all the methods defined inside Interface
.
type IntSlice []int
func (p IntSlice) Len() int { return len(p) }
func (p IntSlice) Less(i, j int) bool { return p[i] < p[j] }
func (p IntSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
In above case you can see that IntSlice
implements the Interface
. Hence you can pass the Intslice
as an argument to Reverse.
As an example you can also implement using Float
values as:
package main
import (
"fmt"
"sort"
)
func main() {
//s := []int{5, 2, 6, 3, 1, 4} // unsorted
s1 := []float64{5.2, 2.6, .6, .03, 2.1 } // unsorted
sort.Sort(sort.Reverse(sort.Float64Slice(s1)))
fmt.Println(s1)
}