go排序示例

zhannk · · 1569 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

package main

import(
        "fmt"
        "sort"
        "math/rand"
)


const(
        male   =  iota
        female
        unknown
)
var genderStr []string=[]string{"male","female","unknown",}



type People struct{
        Id int `ID`
        Age int `Age`
        Name string `Name`
        Gender int `Gender`
}
func (p People) String() string{
        return fmt.Sprintf("People %q of age %v with ID %v,Gender %s\n",p.Name,p.Age,p.Id,genderStr[p.Gender])
}



type Classmate []People
func (c Classmate) Len() int { return len(c) }
func (c Classmate) Less(i,j int) bool { return c[i].Age<c[j].Age }
func (c Classmate) Swap(i,j int) { c[i],c[j]=c[j],c[i] }





func main(){
        cs:=make (Classmate,10,20)


        for  i:=0;i<len(cs); i++ {
                cs[i].Id=i
                cs[i].Age=rand.Intn(50)
                cs[i].Name=fmt.Sprintf("cs_%v",i)
                cs[i].Gender=rand.Intn(3)
        }
        fmt.Println(cs)

        sort.Sort(cs)
        fmt.Println(cs)

}






Screen output sample:

[People "cs_0" of age 31 with ID 0,Gender male
 People "cs_1" of age 47 with ID 1,Gender unknown
 People "cs_2" of age 31 with ID 2,Gender male
 People "cs_3" of age 25 with ID 3,Gender unknown
 People "cs_4" of age 6 with ID 4,Gender male
 People "cs_5" of age 44 with ID 5,Gender female
 People "cs_6" of age 12 with ID 6,Gender unknown
 People "cs_7" of age 28 with ID 7,Gender unknown
 People "cs_8" of age 11 with ID 8,Gender unknown
 People "cs_9" of age 37 with ID 9,Gender unknown
]
[People "cs_4" of age 6 with ID 4,Gender male
 People "cs_8" of age 11 with ID 8,Gender unknown
 People "cs_6" of age 12 with ID 6,Gender unknown
 People "cs_3" of age 25 with ID 3,Gender unknown
 People "cs_7" of age 28 with ID 7,Gender unknown
 People "cs_0" of age 31 with ID 0,Gender male
 People "cs_2" of age 31 with ID 2,Gender male
 People "cs_9" of age 37 with ID 9,Gender unknown
 People "cs_5" of age 44 with ID 5,Gender female
 People "cs_1" of age 47 with ID 1,Gender unknown


有疑问加站长微信联系(非本文作者)

本文来自:CSDN博客

感谢作者:zhannk

查看原文:go排序示例

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1569 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传