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
很难理解函数反转(数据接口)接口是什么意思.
如何反转数组?我不需要分类.
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
很难理解函数反转(数据接口)接口是什么意思.
如何反转数组?我不需要分类.
通常,要对整数数组进行排序,需要将它们包装在IntSlice
中,IntSlice
定义了方法Len
、Less
和Swap
.sort.Sort
依次使用这些方法.sort.Reverse
所做的是,它采用了一个定义Len
、Less
和Swap
的现有类型,但它用一个始终与底层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
,它将按降序排序.