Go 有自动生成吗?
Is there autovivification for Go?
围棋有autovivification吗?
正如@JimB 正确注意到的那样,我的定义并不那么严格。关于我的目标:在 Python 中,我们有一个非常优雅的 "emulation" 用于自动生成:
class Path(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
Go有没有类似的解决方案?
如果键不存在,Go 映射将 return 类型的零值,或者映射是 nil
https://play.golang.org/p/sBEiXGfC1c
var sliceMap map[string][]string
// slice is a nil []string
slice := sliceMap["does not exist"]
var stringMap map[string]string
// s is an empty string
s := stringMap["does not exist"]
由于具有数值 return 的映射将 return 0
用于缺少条目,Go 允许您在不存在的键上使用递增和递减运算符:
counters := map[string]int{}
counters["one"]++
同时扩展 JimB 的答案,结合 map
、interface{}
和 type assertion,您可以动态创建任何复杂的结构:
type Obj map[interface{}]interface{}
func main() {
var o Obj
o = Obj{
"Name": "Bob",
"Age": 23,
3: 3.14,
}
fmt.Printf("%+v\n", o)
o["Address"] = Obj{"Country": "USA", "State": "Ohio"}
fmt.Printf("%+v\n", o)
o["Address"].(Obj)["City"] = "Columbus"
fmt.Printf("%+v\n", o)
fmt.Printf("City = %v\n", o["Address"].(Obj)["City"])
}
输出(在 Go Playground 上尝试):
map[Name:Bob Age:23 3:3.14]
map[Age:23 3:3.14 Address:map[Country:USA State:Ohio] Name:Bob]
map[3:3.14 Address:map[Country:USA State:Ohio City:Columbus] Name:Bob Age:23]
City = Columbus
围棋有autovivification吗?
正如@JimB 正确注意到的那样,我的定义并不那么严格。关于我的目标:在 Python 中,我们有一个非常优雅的 "emulation" 用于自动生成:
class Path(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
Go有没有类似的解决方案?
如果键不存在,Go 映射将 return 类型的零值,或者映射是 nil
https://play.golang.org/p/sBEiXGfC1c
var sliceMap map[string][]string
// slice is a nil []string
slice := sliceMap["does not exist"]
var stringMap map[string]string
// s is an empty string
s := stringMap["does not exist"]
由于具有数值 return 的映射将 return 0
用于缺少条目,Go 允许您在不存在的键上使用递增和递减运算符:
counters := map[string]int{}
counters["one"]++
同时扩展 JimB 的答案,结合 map
、interface{}
和 type assertion,您可以动态创建任何复杂的结构:
type Obj map[interface{}]interface{}
func main() {
var o Obj
o = Obj{
"Name": "Bob",
"Age": 23,
3: 3.14,
}
fmt.Printf("%+v\n", o)
o["Address"] = Obj{"Country": "USA", "State": "Ohio"}
fmt.Printf("%+v\n", o)
o["Address"].(Obj)["City"] = "Columbus"
fmt.Printf("%+v\n", o)
fmt.Printf("City = %v\n", o["Address"].(Obj)["City"])
}
输出(在 Go Playground 上尝试):
map[Name:Bob Age:23 3:3.14]
map[Age:23 3:3.14 Address:map[Country:USA State:Ohio] Name:Bob]
map[3:3.14 Address:map[Country:USA State:Ohio City:Columbus] Name:Bob Age:23]
City = Columbus