1.8以前是使用
//数组对象实现该接口
type Interface interface {
// Len is the number of elements in the collection.
Len() int
// Less reports whether the element with
// index i should sort before the element with index j.
Less(i, j int) bool
// Swap swaps the elements with indexes i and j.
Swap(i, j int)
}
//然后使用
sort.Sort(interface)
//例如
type StringList []string
func (sl StringList )Len() int{
return len(sl)
}
func (sl StringList )Less(i, j int) bool{
return sl[i]
}
func (sl StringList )Swap(i, j int){
var temp string = sl[i]
sl[i] = sl[j]
sl[j] = temp
}
b := StringList{"4","6","5"}
sort.Sort(b)
fmt.Println(b)
1.8新增sort.Slice函数就方便好多了
sort.Slice(s,func(i,j int)bool {return s [i] .Name
a := []string{"1","3","2"}
sort.Slice(a, func(i,j int) bool { return a[i]>a[j]});
完整例子
type StringList []string
func (sl StringList )Len() int{
return len(sl)
}
func (sl StringList )Less(i, j int) bool{
return sl[i]
}
func (sl StringList )Swap(i, j int){
var temp string = sl[i]
sl[i] = sl[j]
sl[j] = temp
}
func main() {
TestSort()
}
func TestSort(){
a := []string{"1","3","2"}
sort.Slice(a, func(i,j int) bool { return a[i]>a[j]});
fmt.Println(a)
b := StringList{"4","6","5"}
sort.Sort(b)
fmt.Println(b)
}