Go Example--自定义排序

时间:2023-03-09 03:31:46
Go Example--自定义排序
package main

import (
"fmt"
"sort"
) //定义类型别名
type ByLength []string func (s ByLength) Len() int {
return len(s)
}
func (s ByLength) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s ByLength) Less(i, j int) bool {
return len(s[i]) < len(s[j])
}
func main() {
fruits := []string{"peach", "banana", "kiwi"}
//强制转换类型,ByLength实现了Interface接口
sort.Sort(ByLength(fruits))
fmt.Println(fruits)
}