码迷,mamicode.com
首页 > 其他好文 > 详细

sorting functions _ golang

时间:2015-03-20 16:17:47      阅读:107      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!