golang 排序 1.8 新特性

前端之家收集整理的这篇文章主要介绍了golang 排序 1.8 新特性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

猜你在找的Go相关文章