Home > Blockchain >  How does Reverse work in Golang under the hood?
How does Reverse work in Golang under the hood?

Time:12-28

s := []string{"Zeno", "John", "Al", "Jenny"}

sort.Sort(sort.Reverse(sort.StringSlice(s)))

I could not understand the logic of Reverse

The source code for Reverse seems as follows:

func Reverse(data Interface) Interface {
    return &reverse{data}
}
type reverse struct {
    // This embedded Interface permits Reverse to use the methods of
    // another Interface implementation.
    Interface
}
type Interface interface {
    // Len is the number of elements in the collection.
    Len() int

    // Less reports whether the element with index i
    // must sort before the element with index j.
    //
    // If both Less(i, j) and Less(j, i) are false,
    // then the elements at index i and j are considered equal.
    // Sort may place equal elements in any order in the final result,
    // while Stable preserves the original input order of equal elements.
    //
    // Less must describe a transitive ordering:
    //  - if both Less(i, j) and Less(j, k) are true, then Less(i, k) must be true as well.
    //  - if both Less(i, j) and Less(j, k) are false, then Less(i, k) must be false as well.
    //
    // Note that floating-point comparison (the < operator on float32 or float64 values)
    // is not a transitive ordering when not-a-number (NaN) values are involved.
    // See Float64Slice.Less for a correct implementation for floating-point values.
    Less(i, j int) bool

    // Swap swaps the elements with indexes i and j.
    Swap(i, j int)
}

How do those given operations above induce the given array to be reversed?

CodePudding user response:

If you look at the sort.StringSlice type, you can see it implements the Less method, notice the comparison x[i] < x[j], which means smaller element goes first.

func (x StringSlice) Less(i, j int) bool { return x[i] < x[j] }

And then notice the sort.reverse type (not sort.Reverse interface), it also implements the Less method but see how it passes the i and j arguments, receives i and j but passes j and i, which is just equivalent to x[i] > x[j]

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