Go的自定义函数排序

  在Java中我们可以使用compareTo() 进行自定义排序,在Go中呢:

package main

import "sort"
import "fmt"

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{"测试1", "测试11", "测试111"}
    sort.Sort(byLength(fruits))
    fmt.Println(fruits)
}

//Go如果是统计Unicode字符长度使用utf8.RuneCountInString方法
//len()方法是计算的ASCII长度

猜你喜欢

转载自www.cnblogs.com/meetzy/p/10516408.html