Equivalent of setdefault in Go?

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.


As far as I know, there isn't something like that built in. You could add a type to help out

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"))
}

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))
}

Tags:

Python

Go