首页 > 其他 > 详细

sorting functions _ golang

时间:2015-03-20 16:16:43      阅读:273      评论:0      收藏:0      [点我收藏+]

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

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"}
    sort.Sort(ByLength(fruits))
    fmt.Println(fruits)
}
[kiwi peach banana]

总结 :

  1 : ...

sorting functions _ golang

原文:http://www.cnblogs.com/jackkiexu/p/4353772.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!