Go 排序

排序
创建于:2020年09月13日

业务开发中需要把首字母相同的用户放在一起,并根据首字母进行排序,需要的数据结构:

[
    {
        letter: A,
        list: [{name: A同学1,age: 15},{name: A同学2,age: 14}]
    },
    {
        letter: B,
        list: [{name: B同学1,age: 16},{name: B同学2,age: 14}]
    }
]
package main

import (
    "fmt"
    "sort"
)

type Person struct{
    Name string
    Age uint8
    Letter string
}

func main(){

    // 数据库中取出的数据
    var list = []Person{
        {Name:"C同学1", Age:18, Letter:"C"},
        {Name:"D同学1", Age:20, Letter:"D"},
        {Name:"C同学2", Age:18, Letter:"C"},
        {Name:"A同学1", Age:16, Letter:"A"},
        {Name:"V同学1", Age:19, Letter:"V"},
        {Name:"C同学3", Age:22, Letter:"C"},
        {Name:"Z同学1", Age:22, Letter:"Z"},
    }

    var personMap = make(map[string][]Person)
    var letterMap = make(map[string]string)

    for _, item := range list{

        if val, ok := personMap[item.Letter]; ok{
            personMap[item.Letter] = append(val, item)
        }else{
            letterMap[item.Letter] = item.Letter
            personMap[item.Letter] = []Person{item}
        }
    }

    var keys []string // 如果是根据int排序则声明 keys 为 []int 类型
    for k := range personMap {
        keys = append(keys, k)
    }

    sort.Strings(keys)

    var result []map[string]interface{}
    for _, k := range keys {

        tempMap := make(map[string]interface{})

        tempMap["letter"] = letterMap[k]
        tempMap["list"] = personMap[k]

        result = append(result, tempMap)
    }

    fmt.Println(result)
}