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?
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"]++
Also extending JimB's answer, with the combination of map
, interface{}
and type assertion, you can dynamically create any complex structures:
type Obj map[interface{}]interface{}
func main() {
var o Obj
o = Obj{
"Name": "Bob",
"Age": 23,
3: 3.14,
}
fmt.Printf("%+v
", o)
o["Address"] = Obj{"Country": "USA", "State": "Ohio"}
fmt.Printf("%+v
", o)
o["Address"].(Obj)["City"] = "Columbus"
fmt.Printf("%+v
", o)
fmt.Printf("City = %v
", o["Address"].(Obj)["City"])
}
Output (try it on the Go Playground):
map[Name:Bob Age:23 3:3.14]
map[Age:23 3:3.14 Address:map[Country:USA State:Ohio] Name:Bob]
map[3:3.14 Address:map[Country:USA State:Ohio City:Columbus] Name:Bob Age:23]
City = Columbus