golang sort

package main

import (
    "fmt" 
    "strings"     
    "sort"
)

type Animals []string

func (a Animals) Len() int           { return len(a) }
func (a Animals) Less(i, j int) bool { return len(a[i]) < len(a[j]) }
func (a Animals) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

func main() {
    animals := []string{"cat", "bird", "zebra", "fox"}
    // Sort by strings.
    sort.Strings(animals)
    fmt.Println(animals)//[bird cat fox zebra]

    //sort by len
    an := Animals{"cat", "bird", "zebra", "fox"}
    sort.Sort(an)
    fmt.Println(an)//[cat fox bird zebra]
}

 

本文来自:博客园

感谢作者:rojas

查看原文:golang sort

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。