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

大家好,我是Golang社区主编彬哥,这篇是给大家讲解关于复杂数据结构排序的。

结构体,数据排序

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 (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)
                // 组合排名
        }

}

输出结果:

调试结果

原创声明,本文系作者授权云+社区发表,未经许可,不得转载。

如有侵权,请联系 yunjia_community@tencent.com 删除。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

扫码关注云+社区