1.Ints,float64s,strings
使用以如函数实现基本类型
-
sort.Ints
-
sort.Float64s
-
sort.Strings
1s := []int{4, 2, 3, 1} 2sort.Ints(s) 3fmt.Println(s) // [1 2 3 4]
2.结构体自定义排序
-
使sort.Slice用函数,它使用提供了less(i int,j int)函数返回布尔值,对切片进行排序
-
若要在保持相等元素的原始顺序的同时对切片进行排序,请使用sort.SliceStable函数
family := []struct { Name string Age int}{ {"Alice", 23}, {"David", 2}, {"Eve", 2}, {"Bob", 25}, }// Sort by age, keeping original order or equal elements.sort.SliceStable(family, func(i, j int) bool { return family[i].Age < family[j].Age }) fmt.Println(family) // [{David 2} {Eve 2} {Alice 23} {Bob 25}]
3.结构体自定义排序2
-
使用通用sort.Sort 和sort.Stable functions排序功能
-
对要排序的集合要实现sort.Interface接口
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) }
一个简单的例子:
1type Person struct { 2 Name string 3 Age int}// ByAge implements sort.Interface based on the Age field.type ByAge []Personfunc (a ByAge) Len() int { return len(a) }func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] }func main() { 4 family := []Person{ 5 {"Alice", 23}, 6 {"Eve", 2}, 7 {"Bob", 25}, 8 } 9 sort.Sort(ByAge(family)) 10 fmt.Println(family) // [{Eve 2} {Alice 23} {Bob 25}]}
4.map排序
map是键值对是一个无序集合。如果需要稳定的迭代顺序,则必须维护独立的数据结构比如:
1m := map[string]int{"Alice": 2, "Cecil": 1, "Bob": 3} 2 3keys := make([]string, 0, len(m))for k := range m { 4 keys = append(keys, k) 5} 6sort.Strings(keys)for _, k := range keys { 7 fmt.Println(k, m[k]) 8}// Output:// Alice 2// Bob 3// Cecil 1
最后
最近在写基于Golang的工具和框架,还请多多Star.
YoyoGo是一个用 Go 编写的简单,轻便,快速的 微服务框架,目前已实现了Web框架的能力,但是底层设计已支持多种服务架构。
Github
https://github.com/yoyofx/yoyogo
https://github.com/yoyofxteam
本文分享自微信公众号 - 晋级CTO(up_cto)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。