前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Golang语言社区--结构体数据排序

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

原创
作者头像
李海彬
发布2018-03-09 22:44:35
7320
发布2018-03-09 22:44:35
举报
文章被收录于专栏:Golang语言社区Golang语言社区

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

结构体,数据排序

代码语言:go
复制
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)
                // 组合排名
        }

}

输出结果:

调试结果
调试结果

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com