Go有自动生存功能吗?
正如@JimB 正确注意到的那样,我的定义并不那么严格。关于我的目标:在 Python 中,我们有一个非常优雅的“仿真”来实现自动激活:
class Path(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
Go有类似的解决方案吗?
Go有自动生存功能吗?
正如@JimB 正确注意到的那样,我的定义并不那么严格。关于我的目标:在 Python 中,我们有一个非常优雅的“仿真”来实现自动激活:
class Path(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
Go有类似的解决方案吗?
如果键不存在,Go maps 将返回该类型的零值,或者 map 是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"]
由于带有数值返回的映射将返回0
丢失的条目,因此 Go 允许您对不存在的键使用递增和递减运算符:
counters := map[string]int{}
counters["one"]++
map
还扩展了 JimB 的答案,结合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