Note that the default behavior of Go should return a value of zero value "for the type of value (for example, 0 or "" ) when the missing control key is missing, so if you want the default, thatβs all, you are already set up.
Having canceled the answers of Buddy and larsmans, enter the code that adds a new method to the named Dict type, so you can 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)) }
source share