如何在 Go 中反转数组?

新手上路,请多包涵

http://play.golang.org/p/W70J4GU7nA

   s := []int{5, 2, 6, 3, 1, 4}
  sort.Reverse(sort.IntSlice(s))
  fmt.Println(s)
  // 5, 2, 6, 3, 1, 4

很难理解它在 func Reverse(data Interface) Interface 中的含义。

如何反转数组?我不需要排序。

原文由 user2671513 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.4k
2 个回答

Normally, to sort an array of integers you wrap them in an IntSlice , which defines the methods Len , Less , and Swap . sort.Sort 依次使用这些方法。 What sort.Reverse does is that it takes an existing type that defines Len , Less , and Swap , but it replaces the Less 一种新的方法,它始终是基础 Less 的逆函数:

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

所以当你写 sort.Reverse(sort.IntSlice(s)) 时,发生的事情是你得到了这个新的,“修改过的” IntSlice 它被替换了 Less 因此,如果您调用 sort.Sort ,调用 Less ,它将按降序排列。

原文由 Muhammad Faizan 发布,翻译遵循 CC BY-SA 3.0 许可协议

老实说,这个很简单,我会像这样写出来:

 package main

import "fmt"

func main() {

    s := []int{5, 2, 6, 3, 1, 4}

    for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
        s[i], s[j] = s[j], s[i]
    }

    fmt.Println(s)
}

http://play.golang.org/p/vkJg_D1yUb

(其他答案很好地解释了 sort.Interface 以及如何使用它;所以我不会重复。)

原文由 Brad Peabody 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏