goautovivification

Is there autovivification for Go?


Is there autovivification for Go?

As @JimB correctly noticed, my definition is not that strict. About my goal: In Python we have a very elegant "emulation" for an autovivification:

class Path(dict):
    def __missing__(self, key):
            value = self[key] = type(self)()
            return value

Is there a similar solution for Go?


Solution

  • Go maps will return a zero value for the type if the key doesn't exist, or the map is nil

    https://play.golang.org/p/sBEiXGfC1c

    var sliceMap map[string][]string
    
    // slice is a nil []string
    slice := sliceMap["does not exist"]
    
    
    var stringMap map[string]string
    
    // s is an empty string
    s := stringMap["does not exist"]
    

    Since a map with numeric values return will return 0 for missing entries, Go lets you use the increment and decrement operators on non-existent keys:

    counters := map[string]int{}
    counters["one"]++