Calculate the number of time values in map changes?

How can I count the number of times value in the map changes?

Hi, @Yo_94, what’s your use case? You could hide your map in a struct and keep a counter there:

type myKey string

type myValue interface{}

type myMapElem struct {
    v myValue
    n int
}

type myMap struct {
    m map[myKey]*myMapElem
}

func (m myMap) get(k myKey) (myValue, bool) {
    e, ok := m.m[k]
    if !ok {
        return nil, false
    }
    return e.v, true
}

func (m myMap) set(k myKey, v myValue) int {
    e, ok := m.m[k]
    if !ok {
        e = new(myMapElem)
        m.m[k] = e
    }
    if v != e.v {
        e.v = v
        e.n++
    }
    return e.n
}
2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.