英文:
Equivalent of setdefault in Go?
问题
我可以这样做:
_, ok := some_go_map[a_key]
来测试键是否存在。
但是我被Python的字典的setdefault
方法宠坏了(如果一个键在字典中没有设置值,就将其设置为给定的默认值,然后获取它;否则只是获取它)。
想知道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?
答案1
得分: 13
请注意,Go的默认行为是在查找的键缺失时返回值类型的“零值”(例如,0
或""
),所以如果你想要的默认值恰好是这个,那么你已经准备好了。
在Buddy和larsmans的答案基础上,以下是一个示例代码,它为一个名为Dict
的类型附加了一个新的方法,这样你就可以使用d[key]
来使用Go的内置行为,或者使用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))
}
英文:
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))
}
答案2
得分: 7
你可以自己定义它:
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
}
但是,不,它不在标准库中。通常,你可以直接内联实现这个功能。
英文:
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.
答案3
得分: 1
据我所知,Go语言中没有内置的类似功能。你可以添加一个类型来帮助实现这个功能。
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"))
}
以上是一个示例代码,通过定义一个名为Default
的结构体类型,并在其中添加一个Get
方法,可以实现获取指定键对应的值的功能。在main
函数中,创建了一个someMap
对象,并调用Get
方法来获取键"foo"
和"doesn't exist"
对应的值。
英文:
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"))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论