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

时间:2022-05-03
本文章向大家介绍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)
                // 组合排名
        }

}

输出结果:

调试结果