Is there something like BidiMap?

Hi i need to do some bi-directional locking and need some caind of the map structure like map [key] [key], are there any thoughts like this in Go? Or what is the best way to do it?

+3


source to share


1 answer


There is no such thing in the language or library (AFAIK), but it's easy enough to implement: just combine the two cards in struct

and make sure they stay in sync. The only problem is that they are difficult to write in general terms, but this can be done with 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
}

      



and etc.

+5


source







All Articles