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 许可协议
Normally, to sort an array of integers you wrap them in an
IntSlice
, which defines the methodsLen
,Less
, andSwap
.sort.Sort
依次使用这些方法。 Whatsort.Reverse
does is that it takes an existing type that definesLen
,Less
, andSwap
, but it replaces theLess
一种新的方法,它始终是基础Less
的逆函数:所以当你写
sort.Reverse(sort.IntSlice(s))
时,发生的事情是你得到了这个新的,“修改过的”IntSlice
它被替换了Less
因此,如果您调用sort.Sort
,调用Less
,它将按降序排列。