I can do:
_, ok := some_go_map[a_key]
to test for existence of key.
But I've been spoiled by Python's dict's setdefault
method (if a key does not have value set in a "map" [dict == associative array], set it to a given default, then get it; otherwise just get).
Wondering if there's some idiom in Go to achieve the same thing?
Go by Example: Maps Maps are Go's built-in associative data type (sometimes called hashes or dicts in other languages). To create an empty map, use the builtin make : make(map[key-type]val-type) . Set key/value pairs using typical name[key] = val syntax. Printing a map with e.g. fmt.
The zero value is: 0 for numeric types, false for the boolean type, and.
The string is an inbuilt data type in Go language. The default value of a string variable is an empty string.
Note that Go's default behavior is to return the "zero value" for the value type (e.g., 0
or ""
) when a looked-up key's missing, so if the default you want happens to be that, you're all set already.
Riffing off Buddy and larsmans' answers, here's code that attaches a new method to a named Dict
type, so you can either use d[key]
for Go's built-in behavior or d.SetDefault(key, val)
--
http://play.golang.org/p/5SIJSWNWO7
package main
import "fmt"
type Dict map[string]float64
func (d Dict) SetDefault(key string, val float64) (result float64) {
if v, ok := d[key]; ok {
return v
} else {
d[key] = val
return val
}
}
func main() {
dd := Dict{}
dd["a"] = 3
fmt.Println(dd.SetDefault("a", 1))
fmt.Println(dd.SetDefault("b", 2))
}
You can always define it yourself:
func setDefault(h map[string]int, k string, v int) (set bool, r int) {
if r, set = h[k]; !set {
h[k] = v
r = v
set = true
}
return
}
But no, it's not in the stdlib. Usually, you'd just do this inline.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With