golang 排序 1.8 新特性
发布时间:2020-12-16 18:19:17 所属栏目:大数据 来源:网络整理
导读: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// Swa
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]<sl[j]; } 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 <s [j] .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){ var temp string = sl[i] sl[i] = sl[j] sl[j] = temp } func main() { TestSort() } func TestSort(){ a := []string{"1","2"} sort.Slice(a,j int) bool { return a[i]>a[j]}); fmt.Println(a) b := StringList{"4","5"} sort.Sort(b) fmt.Println(b) } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |