我是 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.