注意:字符串排序是按照ASCII排序
package main
import (
"fmt"
"sort"
)
func main() {
ints := []int{7, 3, 5, 2, 4, 1, 6, 9, 8}
float64s := []float64{3.14, 2.8, 1.6, 0.4, 0.2, 6.5, 5.68}
stringS := []string{"wo", "ai", "golang", "he", "c++"}
//1. int float64 string 升序
sort.Ints(ints)
sort.Float64s(float64s)
sort.Strings(stringS) //ASCII
fmt.Println("int 升序:", ints) //[1 2 3 4 5 6 7 8 9]
fmt.Println("float64 升序:", float64s) //[0.2 0.4 1.6 2.8 3.14 5.68 6.5]
fmt.Println("string 升序:", stringS) //[ai c++ golang he wo]
//2. int float64 string 降序
sort.Sort(sort.Reverse(sort.IntSlice(ints)))
sort.Sort(sort.Reverse(sort.Float64Slice(float64s)))
sort.Sort(sort.Reverse(sort.StringSlice(stringS)))
fmt.Println("int 降序:", ints) //[9 8 7 6 5 4 3 2 1]
fmt.Println("float64 降序:", float64s) //[6.5 5.68 3.14 2.8 1.6 0.4 0.2]
fmt.Println("string 降序:", stringS) //[wo he golang c++ ai]
//3.结构体排序
user := []struct {
Name string
Age int
}{
{"Gopher", 7},
{"Alice", 55},
{"Vera", 24},
{"Bob", 75},
}
// Name升序
sort.Slice(user, func(i, j int) bool { return user[i].Name < user[j].Name })
fmt.Println("name升序:", user) //[{Alice 55} {Bob 75} {Gopher 7} {Vera 24}]
// 年龄降序
sort.Slice(user, func(i, j int) bool { return user[i].Age > user[j].Age })
fmt.Println("age降序:", user) //[{Bob 75} {Alice 55} {Vera 24} {Gopher 7}]
}