码迷,mamicode.com
首页 > 编程语言 > 详细

Go Example--自定义排序

时间:2018-10-23 16:27:04      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:pac   ring   类型   type   inter   func   接口   ace   ret   

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

Go Example--自定义排序

标签:pac   ring   类型   type   inter   func   接口   ace   ret   

原文地址:https://www.cnblogs.com/promenader/p/9837161.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!