有类似BidiMap的东西吗?

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

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.

huangapple
  • 本文由 发表于 2013年2月19日 07:12:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/14947014.html
匿名

发表评论

匿名网友

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

确定