go语言使用sort.Slice给数组排序

创建用户结构体,用户列表按照年龄从小到大排序

package main

import (
	"fmt"
	"sort"
)

type User struct {
	Name string
	Age  int64
}

var UserList []*User

func CreateUser(name string, age int64) *User {
	return &User{
		Name: name,
		Age:  age,
	}
}

func main() {
	user1 := CreateUser("Mike", 28)
	user2 := CreateUser("John", 19)
	user3 := CreateUser("Chen", 30)
	user4 := CreateUser("Corleone", 24)
	UserList = append(UserList, user1)
	UserList = append(UserList, user2)
	UserList = append(UserList, user3)
	UserList = append(UserList, user4)
	for i := 0; i < len(UserList); i++ {
		fmt.Printf("%d: %v\n", i+1, *UserList[i])
	}
	sort.Slice(UserList, func(i, j int) bool {
		return UserList[i].Age < UserList[j].Age
	})
	fmt.Println("按照年龄排序后:")
	for i := 0; i < len(UserList); i++ {
		fmt.Printf("%d: %v\n", i+1, *UserList[i])
	}
}

输出结果

1: {Mike 28}
2: {John 19}
3: {Chen 30}
4: {Corleone 24}
按照年龄排序后:
1: {John 19}
2: {Corleone 24}
3: {Mike 28}
4: {Chen 30}

你可能感兴趣的:(golang,开发语言,后端)