按排序键顺序遍历任意地图

按排序键顺序遍历任意地图

本文介绍了golang:按排序键顺序遍历任意地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单来说,不管地图类型如何,按照排序的顺序遍历地图?



我发现了一些相关的问题,,表明它不能不依赖反映模块。这个理解是否正确?



考虑这个Go代码,按照他们的键的排序顺序遍历两个不同类型的地图:

  mapOne:= map [int] string {
1:a,
2:b,
3: c,
}
keysOne:= make([] int,0,len(mapOne))
为key,_:= range mapOne {
keysOne = append(keysOne ,key)
}
sort.Ints(keysOne)
for _,key:= range keysOne {
value:= mapOne [key]
fmt.Println key,value)
}

mapTwo:= map [string] int {
a:1,
b:2,
c:3,
}
keysTwo:= make([] string,0,len(mapTwo))
为key,_:= range mapTwo {
keysTwo = append(keysTwo,key)
}
sort.Strings(keysTwo)
for _,key:= range keysTwo {
value:= mapTwo [key]
fmt .Println(key,value)
}

解压缩然后排序的逻辑他们被复制为两个
不同的地图PES。 有没有办法解决这个逻辑,并避免
重复?



我陷入了试图写一个界面来提供 SortedKeys 方法。在
特定的情况下,返回类型 SortedKeys 取决于地图的类型,
,我不知道如何在Go中表达

解决方案

我认为谁告诉你,你需要反映正确;这可能是过度杀伤。我认为这里的复制是可以接受的。



(或者,您可以实现自己的地图,使用某种接口的键,但是您仍然需要做一个满足每个底层密钥类型的接口的类型)


In short: How do I traverse a map in sorted key order, regardless of the map's type?

I found a few related questions, the closest one suggesting that it can't be done without relying on the reflect module. Is this understanding correct?

Consider this Go code, which traverses two maps of different types, in sorted order of their keys:

mapOne := map[int]string {
    1: "a",
    2: "b",
    3: "c",
}
keysOne := make([]int, 0, len(mapOne))
for key, _ := range mapOne {
    keysOne = append(keysOne, key)
}
sort.Ints(keysOne)
for _, key := range keysOne {
    value := mapOne[key]
    fmt.Println(key, value)
}

mapTwo := map[string]int {
    "a": 1,
    "b": 2,
    "c": 3,
}
keysTwo := make([]string, 0, len(mapTwo))
for key, _ := range mapTwo {
    keysTwo = append(keysTwo, key)
}
sort.Strings(keysTwo)
for _, key := range keysTwo {
    value := mapTwo[key]
    fmt.Println(key, value)
}

The logic to extract the keys and then sort them is duplicated for the twodifferent map types. Is there any way to factor out this logic and avoidduplication?

I got stuck trying to write an interface to provide a SortedKeys method. Inparticular, the return type of SortedKeys depends on the type of the map,and I can't figure out how to express that in Go.

解决方案

I think whoever told you you'd need reflect was correct; that's probably overkill though. I think the duplication is acceptable here.

(alternatively, you could implement your own map that uses some kind of interface for keys, but you'd still end up needing to make a type that satisfies the interface for each underlying key type)

这篇关于golang:按排序键顺序遍历任意地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 07:16