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)
相关推荐
ttwuai5 天前
Go开源后台管理系统推荐:怎么按技术栈和边界比较4个官方仓库?
golang·gin
codeejun5 天前
每日一Go·MySQL-5、锁机制全解析
云原生·golang
Achou.Wang5 天前
k8s中nginx worker process自动设置
后端·golang
指尖的爷6 天前
ARM 架构 Ubuntu(RK3588/aarch64)go开发环境安装手册
ubuntu·架构·golang
名字还没想好☜6 天前
Go 实现指数退避重试:context 取消、抖动 jitter 与什么时候别重试
后端·golang·go
Casbin开源社区6 天前
OpenAgent 详解:单二进制自托管 AI Agent 平台,30+ 模型接入、RAG 知识库、MCP 工具调用与 Casbin 工具权限
人工智能·golang·开源
五彩小白7 天前
GO语言装饰器语法
golang
金金计较.7 天前
Go语言-4
开发语言·golang
名字还没想好☜7 天前
Go context.AfterFunc 实战(Go 1.21):context 一取消就自动跑清理,告别手写 goroutine 监听 Done
后端·golang·go
web守墓人8 天前
【goed/ui】自定义组件设计思想篇
linux·windows·ui·golang