Go map如何排序

1. 将key 或 value 单独组成其类型的切片或数组,进行排序

go 复制代码
package main

import (
	"fmt"
	"sort"
)

func main() {
	table := map[string]string{
		"hello": "hello",
		"world": "world",
		"a":     "a",
		"b":     "b",
		"c":     "c",
		"d":     "d",
	}

	var keys, values []string

	for k, v := range table {
		keys = append(keys, k)
		values = append(values, v)
	}

	sort.Slice(keys, func(i, j int) bool {
		if keys[i] < keys[j] {
			//keys[i], keys[j] = keys[j], keys[i]
			values[i], values[j] = values[j], values[i]
			return true
		}
		return false
	})

	fmt.Println(keys)
	fmt.Println(values)
}

可以根据有序的key,找到对应的value

go 复制代码
    for _, key := range keys {
         fmt.Println(table[key])
    }

2. 将key,value放入结构体,对结构体切片排序,既可以对key排序,又可以对value排序

go 复制代码
	type Entity struct {
		K string
		V string
	}
	
	table := map[string]string{
		"hello": "hello",
		"world": "world",
		"a":     "a",
		"b":     "b",
		"c":     "c",
		"d":     "d",
	}

	var entities []Entity
	
	for k, v := range table {
		entities = append(entities, Entity{k, v})
	}

	sort.Slice(entities, func(i, j int) bool {
		return entities[i].K < entities[j].K
	})

	fmt.Println(entities)
相关推荐
o0o_-_3 小时前
【go/gopls/mcp】官方gopls内置mcp server使用
开发语言·后端·golang
又菜又爱玩呜呜呜~1 天前
go使用反射获取http.Request参数到结构体
开发语言·http·golang
希望20171 天前
Golang | http/server & Gin框架简述
http·golang·gin
NG WING YIN1 天前
Golang關於信件的
开发语言·深度学习·golang
silver98862 天前
再谈golang的sql链接dsn
mysql·golang
刘媚-海外2 天前
Go语言开发AI应用
开发语言·人工智能·golang·go
deepwater_zone2 天前
Go语言核心技术
后端·golang
二哈不在线2 天前
代码随想录二刷之“动态规划”~GO
算法·golang·动态规划