在部分键上使用元组键访问地图

huangapple go评论79阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2021年12月25日 02:57:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/70475866.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定