go - 如何反转 golang map 中项目的顺序?

标签 go

<分区>

我是 golang 的新手,我想颠倒映射中对的出现顺序,以便最后一对排在第一位:

mapA := map[string]int {
    "cat": 5,
    "dog": 2,
    "fish": 3 ,
}


fmt.Println(mapA)


map[cat:5 dog:2 fish:3]

生成的 map 应该是这样的:

map[fish:3 dog:2 cat:5]

它可以是一个新的 mapB,具有相同的项目但顺序颠倒。

我怎样才能做到这一点?

最佳答案

The Go Programming Language Specification

Map types

A map is an unordered group of elements.

For statements

The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next.


你不能。未订购 Go map 。一个Go map是一个hash map(哈希表)。

要按顺序(或倒序)获取 map 内容,请将 map 内容读取到 slice 中并对其进行排序。


Hash table - Wikipedia

A hash table uses a hash function to compute an index into an array of buckets or slots, from which the desired value can be found.

Drawbacks

The entries stored in a hash table can be enumerated efficiently (at constant cost per entry), but only in some pseudo-random order. Therefore, there is no efficient way to locate an entry whose key is nearest to a given key. Listing all n entries in some specific order generally requires a separate sorting step, whose cost is proportional to log(n) per entry.

关于go - 如何反转 golang map 中项目的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51228962/

相关文章:

go - 与Google Photos API的竞争条件

python - 如何从 go 语言的 main 中获取不同的退出代码,如 2 或 3?

go - GoCD中的参数化管道?

pointers - 将指针传递给 Golang 中的 map

http - 如何将 context.Done() 与嵌套的 http 中间件一起使用

go - 在golang中ec2.CreateSecurityGroup中的名称类型是什么

go - 如何在 golang 中验证图片 url?

regex - golang正则表达式删除所有空白行

go - 在 Go 中如何遍历指针列表?

go - 如何从另一个文件或包导入 gorm db 连接