【问题标题】:How does Reverse work in Golang under the hood?Reverse 在 Golang 的底层是如何工作的?
【发布时间】:2022-01-26 12:06:27
【问题描述】:
s := []string{"Zeno", "John", "Al", "Jenny"}

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

看不懂Reverse的逻辑

Reverse 的源代码如下:

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

以上给定的操作如何导致给定的数组反转?

【问题讨论】:

  • reverse这个接口的实现。我打赌它只是颠倒了Less 的逻辑。
  • 所有与问题相关的实现都已经列出来了,伙计。如果有任何遗漏,您可以肯定地通知我。
  • reverse.Less 方法在调用底层 Less 方法时交换参数顺序。
  • @ibrahimkoz 缺少接口的实现。您发布的是声明。它有几个方法的签名,但是这些方法的代码在哪里?
  • @ibrahimkoz 您显然对interfacesort.Interface 感到困惑。这些是不同的东西。无论如何,@Cerise 已经发布了一个回答问题的实现链接(并证实了我的猜测)

标签: go reverse


【解决方案1】:

如果你查看 sort.StringSlice 类型,你可以看到它实现了 Less 方法,注意比较 x[i]

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

然后注意 sort.reverse 类型(不是 sort.Reverse 接口),它也实现了 Less 方法,但看看它如何传递 i 和 j 参数,接收 i 和 j 但传递 j 和 i,这只是等价的到 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)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-17
    • 1970-01-01
    • 2015-06-02
    • 2020-11-30
    • 2014-08-11
    • 1970-01-01
    相关资源
    最近更新 更多