英文:
golang: traverse arbitrary map in sorted key order
问题
简而言之:无论地图的类型如何,我如何按排序的键顺序遍历地图?
我找到了一些相关的问题,最接近的一个建议在不依赖于reflect
模块的情况下无法完成。这个理解正确吗?
考虑以下Go代码,它按照键的排序顺序遍历了两个不同类型的地图:
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)
}
提取键然后对它们进行排序的逻辑在两种不同的地图类型中重复。有没有办法将这个逻辑提取出来并避免重复?
我在尝试编写一个接口来提供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 two
different map types. Is there any way to factor out this logic and avoid
duplication?
I got stuck trying to write an interface to provide a SortedKeys
method. In
particular, the return type of SortedKeys
depends on the type of the map,
and I can't figure out how to express that in Go.
答案1
得分: 2
我认为告诉你需要使用reflect
的人是正确的;不过这可能有点过度设计。我认为在这里重复是可以接受的。
(或者,你可以实现自己的映射,使用某种接口作为键,但你仍然需要为每个底层键类型创建满足接口的类型)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论