有没有autovivification围棋?
正如@JimB 正确注意到的那样,我的定义并不那么严格。关于我的目标:在 Python 中,我们有一个非常优雅的“仿真” 用于自动生成:
class Path(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
Go 有类似的解决方案吗?
最佳答案
如果键不存在,或者映射为 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"]++
关于go - Go 有自动生成吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41399222/