3

【笔记】Go结构体自定义排序

 1 year ago
source link: https://blog.loli.fj.cn/2023/05/16/Go%E7%BB%93%E6%9E%84%E4%BD%93%E8%87%AA%E5%AE%9A%E4%B9%89%E6%8E%92%E5%BA%8F/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

【笔记】Go结构体自定义排序

2023-05-16

Go通过实现接口实现结构体自定义排序

定义自定义结构体

type User struct {
Id int
}

type UserSlice []User
// Len 获取切片长度
func (userSlice UserSlice) Len() int {
return len(userSlice)
}

// Less 定义排序条件,如果返回false,就进行位置交换
func (userSlice UserSlice) Less(i, j int) bool {
return userSlice[i].Id < userSlice[j].Id
}

// Swap 定义元素交换方式
func (userSlice UserSlice) Swap(i, j int) {
userSlice[i], userSlice[j] = userSlice[j], userSlice[i]
}

调用排序方法

// 定义变量
var users = UserSlice{User{2}, User{1}, User{3}}
// 进行排序
sort.Sort(users)

哔哩哔哩——尚硅谷


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK