英文:
Access to the map with a tuple key on partial key
问题
我有一个具有元组键({int,string})的地图:
NWKey结构体 {
deviceId int64
interfaceType string
}
m = make(map[NWKey]int, 0)
我需要获取地图的部分键元素,类似于{int,},其中表示键的这部分不重要。在Goland中是否可以实现这一点?如果可以,请解释如何实现。
英文:
I have a map with tuple key {int, string}:
NWKey struct {
deviceId int64
interfaceType string
}
m = make(map[NWKey]int, 0)
I need to get map's elements for partial key, something like this {int, *}, where * means this part of key isn't matter. Is it possible in goland to do it& If yes please explain how to do it.
答案1
得分: 1
只使用直接查找是不可能的。一个问题是可能存在多个具有相同deviceId的键。
相反,你需要遍历你的映射,并找到正确的id。例如:
wantedId := 532
for key, value := range m {
if key.deviceId == wantedId {
// 在这里执行你想要的操作
}
}
然而,这在一定程度上减少了映射的用途。你可以考虑重构你的结构,只将deviceId作为键(map[int64]int),但这可能对你不起作用。
英文:
It is not possible with just a direct lookup. One problem is that there could exist multiple keys with the same deviceId.
Instead what you would need to do is to iterate over your map and find the with the correct id. For example:
wantedId := 532
for key, value := range m {
if key.deviceId == wantedId {
// Do what you want to do here
}
}
However, this does partly remove the use case for maps. You could reconsider refactoring your struct to only have the deviceId as key (map[int64]int), but this might not work for you.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论