英文:
Is there something like a BidiMap?
问题
嗨,我需要进行一些双向查找,并且需要一种类似于map[key][key]的映射结构。在Go语言中有类似的东西吗?或者有什么最好的方法来实现它?
英文:
Hi I need to do some bidirectional lockup and need some caind of map structure like map[key][key] are there some think like that in Go? Or what is the best way to go about doing it?
答案1
得分: 5
在语言或库中没有这样的东西(据我所知),但它们很容易实现:只需在一个struct
中组合两个映射,并确保它们保持同步。唯一的问题是很难以通用的方式编写这些,但可以使用interface{}
来实现:
type BidirMap struct {
left, right map[interface{}]interface{}
}
func (m *BidirMap) Insert(key, val interface{}) {
if _, inleft := left[key]; inleft {
delete(left, key)
}
if _, inright := right[val]; inright {
delete(right, val)
}
m.left[key] = val
m.right[val] = key
}
等等。
英文:
There's no such thing in the language or the library (AFAIK), but they're easy enough to implement: just combine two maps in a struct
and make sure they stay in sync. The only problem is that it's hard to write these in a generic manner, but that can be done using interface{}
:
type BidirMap struct {
left, right map[interface{}]interface{}
}
func (m *BidirMap) Insert(key, val interface{}) {
if _, inleft := left[key]; inleft {
delete(left, key)
}
if _, inright := right[val]; inright {
delete(right, val)
}
m.left[key] = val
m.right[val] = key
}
etc.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论