欢迎访问Ningto's博客

Menu
  • 首页
  • 归档
  • 关于
  • 书签
  • 必应壁纸
  • IT聚合
  • 工具
    • 我的工具列表
    • 我的网盘
    • 必应每日壁纸API
    • Html转Markdown
    • 仙尘光标
Menu

go常见排序方法

最后更新 2019-05-10 09:01:11   阅读量 1529

golang排序写法还是蛮简洁的,不管是简单类型还是复杂的结构,倒序排序的时候可能有点奇怪不知道为什么这样设计

package main

import (
    "fmt"
    "sort"
)

type Person struct {
    Name string
    Age  int
}

func main() {
    // 整型排序
    intList := []int{3, 5, 1, 3, 6, 4, 65, 1}
    fmt.Println("int排序前:", intList)
    sort.Sort(sort.IntSlice(intList)) // 简洁写法:sort.Ints(intList)
    fmt.Println("int排序后:", intList)
    sort.Sort(sort.Reverse(sort.IntSlice(intList)))
    fmt.Println("int倒序排序后:", intList)
    fmt.Println("-------------------------------------------")

    // 字符串排序
    strList := []string{"aaa", "ccc", "eee", "bbbb", "dddd"}
    fmt.Println("字符串排序前:", strList)
    sort.Sort(sort.StringSlice(strList)) // 简洁写法:sort.Strings(strList)
    fmt.Println("字符串排序后:", strList)
    sort.Sort(sort.Reverse(sort.StringSlice(strList)))
    fmt.Println("字符串倒序排序后:", strList)
    fmt.Println("-------------------------------------------")

    // 结构体排序
    p1 := Person{"foo", 31}
    p2 := Person{"wff", 33}
    p3 := Person{"bob", 32}
    personList := []Person{p1, p2, p3}
    fmt.Println("结构体排序前:", personList)

    sort.Slice(personList, func(i int, j int) bool {
        return personList[i].Name < personList[j].Name
    })
    fmt.Println("结构体名字排序后:", personList)

    sort.Slice(personList, func(i int, j int) bool {
        return personList[i].Name > personList[j].Name
    })
    fmt.Println("结构体名字倒序排序后:", personList)

    sort.Slice(personList, func(i int, j int) bool {
        return personList[i].Age < personList[j].Age
    })
    fmt.Println("结构体年龄排序后:", personList)

    sort.Slice(personList, func(i int, j int) bool {
        return personList[i].Age > personList[j].Age
    })
    fmt.Println("结构体年龄倒序排序后:", personList)
}

输出结果:

int排序前: [3 5 1 3 6 4 65 1]
int排序后: [1 1 3 3 4 5 6 65]
int倒序排序后: [65 6 5 4 3 3 1 1]
-------------------------------------------
字符串排序前: [aaa ccc eee bbbb dddd]
字符串排序后: [aaa bbbb ccc dddd eee]
字符串倒序排序后: [eee dddd ccc bbbb aaa]
-------------------------------------------
结构体排序前: [{foo 31} {wff 33} {bob 32}]
结构体名字排序后: [{bob 32} {foo 31} {wff 33}]
结构体名字倒序排序后: [{wff 33} {foo 31} {bob 32}]
结构体年龄排序后: [{foo 31} {bob 32} {wff 33}]
结构体年龄倒序排序后: [{wff 33} {bob 32} {foo 31}]
(转载本站文章请注明作者和出处:泞途 - ningto.com)

下一篇 – go学习代码片段
上一篇 – go 连接池

  1. Go

toningto@outlook.com

推荐文章

beast websocket demo

降权启动应用

标签云

Others Qt Go Web Product Javascript Mobile Linux Database Node.js Tools Design MQ Java Shell Bug Android Mac MongoDB Python C/C++ Tips Windows Life React Boost IOS

推广链接

【腾讯云】云产品限时秒杀,爆款1核2G云服务器,首年99元

多谢支持,用了好几年,服务很稳定支持多设备!

其他

文章RSS

Copyright © 2016 Welcome To Ningto Blog | 鄂ICP备17003086号-2