Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of setdefault in Go?

Tags:

python

go

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?

like image 948
LetMeSOThat4U Avatar asked Nov 27 '13 19:11

LetMeSOThat4U


People also ask

How do you create a map in go?

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.

What is the default value of type bool in Go programming?

The zero value is: 0 for numeric types, false for the boolean type, and.

What are the default values of these types string * string in Golang?

The string is an inbuilt data type in Go language. The default value of a string variable is an empty string.


2 Answers

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))
}
like image 101
twotwotwo Avatar answered Oct 20 '22 06:10

twotwotwo


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.

like image 24
Fred Foo Avatar answered Oct 20 '22 06:10

Fred Foo