原文地址:http://www.golang.ltd/forum.php?mod=viewthread&tid=2816&extra=page%3D1
作者:彬哥
结构体,数据排序
- package main
-
- import (
- "fmt"
- "sort"
- "strconv"
- )
-
- var testmap map[string]Person
-
- type Person struct {
- Name string
- Age int
- Sex string
- }
- type ByAge []Person
-
- func (a ByAge) Len() int { return len(a) }
- func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
-
- func (a ByAge) Less(i, j int) bool { return a[i].Age > a[j].Age } // 从大到小排序
-
- func init() {
- testmap = make(map[string]Person)
- var testmap1 Person
-
- testmap1.Name = "John"
- testmap1.Age = 31
- testmap1.Sex = "1"
- testmap["3"] = testmap1
-
- testmap1.Name = "Bob1"
- testmap1.Age = 31
- testmap1.Sex = "1"
- testmap["0"] = testmap1
-
- testmap1.Name = "Bob"
- testmap1.Age = 31
- testmap1.Sex = "1"
- testmap["2"] = testmap1
-
-
- testmap1.Name = "John1"
- testmap1.Age = 31
- testmap1.Sex = "1"
- testmap["4"] = testmap1
-
- testmap1.Name = "John2"
- testmap1.Age = 31
- testmap1.Sex = "1"
- testmap["5"] = testmap1
-
- testmap1.Name = "John3"
- testmap1.Age = 31
- testmap1.Sex = "1"
- testmap["6"] = testmap1
-
- }
-
- func main() {
- fmt.Println(len(testmap))
- people := make([]Person, len(testmap))
- // 1 结构提取值获取数据 append
- for key, second := range testmap {
- ikey, _ := strconv.Atoi(key)
- fmt.Println(people) // 从0开始的
- people = append(people, people[ikey])
- people[ikey] = second
- }
- // 排序
- sort.Sort(ByAge(people))
- fmt.Println(people)
- // 获取数据值
- for key, second := range people {
- fmt.Println(key) // 从0开始的
- fmt.Println(second.Name)
-
- }
-
- }