go - Go 有自动生成吗?

标签 go autovivification

有没有autovivification围棋?

正如@JimB 正确注意到的那样,我的定义并不那么严格。关于我的目标:在 Python 中,我们有一个非常优雅的“仿真” 用于自动生成:

class Path(dict):
    def __missing__(self, key):
            value = self[key] = type(self)()
            return value

Go 有类似的解决方案吗?

最佳答案

如果键不存在,或者映射为 nil

,Go 映射将返回该类型的零值

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/

相关文章:

xml - Golang 如果为空则隐藏 XML 父标签

networking - 如何在 net.Conn 上执行非阻塞写入?

apache - autovivication.pm 中的 Perl cgi 编译错误

javascript - 自动生成和 Javascript

perl - 迭代时无意中将键添加到哈希

http - 禁用公用名验证 - Go HTTP 客户端

javascript - 将用户 ID 传递给 core-ajax 方法 GET 以检索 Google Cloud 存储中的数据

go - 发生http超时时,如何获取json.NewDecoder(body).Decode()的错误原因?

perl - 为什么 `exists` 修改我的常量?

perl - "no autovivication"杂注在 Perl 中使用 grep 失败