代码拉取完成,页面将自动刷新
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)
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。