1 Star 0 Fork 0

c01dface/s-go-example

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
sorting-by-functions.go 1.07 KB
一键复制 编辑 原始数据 按行查看 历史
c01dface 提交于 2024-12-10 19:36 . add sorting-by-functions.go
package main
// Sometimes we'll want to sort a collection by something other
// than its natural order. For example, suppose we wanted to sort
// strings by their length instead of alphabetically. Here's an
// example of custom sorts in Go.
import (
"cmp"
"fmt"
"slices"
)
func main() {
fruits := []string{"peach", "banana", "kiwi"}
// We implement a comparison function for string lengths
// cmp.Compare is helpful for this.
lenCmp := func(a, b string) int {
return cmp.Compare(len(a), len(b))
}
// Now we can call slices.SortFunc with this custom
// comparison function to sort fruits by name length
slices.SortFunc(fruits, lenCmp)
fmt.Println(fruits)
// we can use the same technique to sort a slice of values
// that aren't built-in types
type Person struct {
name string
age int
}
people := []Person{
Person{name: "Jax", age: 37},
Person{name: "TJ", age: 25},
Person{name: "Alex", age: 72},
}
// sort people by age using slices.SortFunc
slices.SortFunc(people,
func(a, b Person) int {
return cmp.Compare(a.age, b.age)
})
fmt.Println(people)
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/vmalloc/s-go-example.git
git@gitee.com:vmalloc/s-go-example.git
vmalloc
s-go-example
s-go-example
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385