Golang语言社区--结构体数据排序

原文地址:http://www.golang.ltd/forum.php?mod=viewthread&tid=2816&extra=page%3D1

作者:彬哥


结构体,数据排序

  1. package main

  2. import (
  3.         "fmt"
  4.         "sort"
  5.         "strconv"
  6. )

  7. var testmap map[string]Person

  8. type Person struct {
  9.         Name string
  10.         Age  int
  11.         Sex  string
  12. }
  13. type ByAge []Person

  14. func (a ByAge) Len() int      { return len(a) }
  15. func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] }

  16. func (a ByAge) Less(i, j int) bool { return a[i].Age > a[j].Age } // 从大到小排序

  17. func init() {
  18.         testmap = make(map[string]Person)
  19.         var testmap1 Person

  20.         testmap1.Name = "John"
  21.         testmap1.Age = 31
  22.         testmap1.Sex = "1"
  23.         testmap["3"] = testmap1

  24.         testmap1.Name = "Bob1"
  25.         testmap1.Age = 31
  26.         testmap1.Sex = "1"
  27.         testmap["0"] = testmap1

  28.         testmap1.Name = "Bob"
  29.         testmap1.Age = 31
  30.         testmap1.Sex = "1"
  31.         testmap["2"] = testmap1


  32.         testmap1.Name = "John1"
  33.         testmap1.Age = 31
  34.         testmap1.Sex = "1"
  35.         testmap["4"] = testmap1

  36.         testmap1.Name = "John2"
  37.         testmap1.Age = 31
  38.         testmap1.Sex = "1"
  39.         testmap["5"] = testmap1

  40.         testmap1.Name = "John3"
  41.         testmap1.Age = 31
  42.         testmap1.Sex = "1"
  43.         testmap["6"] = testmap1

  44. }

  45. func main() {
  46.         fmt.Println(len(testmap))
  47.         people := make([]Person, len(testmap))
  48.         // 1 结构提取值获取数据 append
  49.         for key, second := range testmap {
  50.                 ikey, _ := strconv.Atoi(key)
  51.                 fmt.Println(people) // 从0开始的
  52.                 people = append(people, people[ikey])
  53.                 people[ikey] = second
  54.         }
  55.         // 排序
  56.         sort.Sort(ByAge(people))
  57.         fmt.Println(people)
  58.         // 获取数据值
  59.         for key, second := range people {
  60.                 fmt.Println(key) // 从0开始的
  61.                 fmt.Println(second.Name)
  62.                 
  63.         }

  64. }
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值