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

前端之家收集整理的这篇文章主要介绍了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. Ageint
  11. Sexstring
  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. testmap["0"] = testmap1
  26. testmap1.Name = "Bob"
  27. testmap["2"] = testmap1
  28. testmap1.Name = "John1"
  29. testmap["4"] = testmap1
  30. testmap1.Name = "John2"
  31. testmap["5"] = testmap1
  32. testmap1.Name = "John3"
  33. testmap["6"] = testmap1
  34. }
  35. func main() {
  36. fmt.Println(len(testmap))
  37. people := make([]Person,len(testmap))
  38. // 1 结构提取值获取数据 append
  39. for key,second := range testmap {
  40. ikey,_ := strconv.Atoi(key)
  41. fmt.Println(people) // 从0开始的
  42. people = append(people,people[ikey])
  43. people[ikey] = second
  44. }
  45. // 排序
  46. sort.Sort(ByAge(people))
  47. fmt.Println(people)
  48. // 获取数据值
  49. fmt.Println(key) // 从0开始的
  50. fmt.Println(second.Name)

  51. }
复制代码
原文链接:https://www.f2er.com/go/187892.html

猜你在找的Go相关文章