Is there something like a BidiMap?

data-structures, go

Solution

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.

Problem

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?

Original source