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)
}

猜你喜欢

转载自www.cnblogs.com/promenader/p/9837161.html
今日推荐