Equivalent to setdefault in Go?

I can do:

_, ok := some_go_map[a_key] 

check for a key.

But I was corrupted by the Python method dict setdefault (if the key does not have the value specified in the "map" [dict == associative array], set it to the default value and then get it, otherwise just get it).

I wonder if there is any idiom in Go to achieve the same?

+6
source share
3 answers

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, this is not in stdlib. Usually you just do it inline.

+6
source

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)) } 
+5
source

As far as I know, this is not built-in. You can add a type that helps

http://play.golang.org/p/pz34p7w6fP

 package main import "fmt" type Default struct { vals map[string]int defaults int } func (d *Default) Get(key string) int { if val, ok := d.vals[key]; ok { return val } return d.defaults } func main() { someMap := Default{map[string]int{"foo": 1, "bar": 2}, 5} fmt.Println(someMap.Get("foo")) fmt.Println(someMap.Get("doesn't exist")) } 
+1
source

Source: https://habr.com/ru/post/958948/


All Articles