Go有自动化吗?

时间:2016-12-30 16:11:15

标签: go autovivification

Go有autovivification吗?

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

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

Go有类似的解决方案吗?

2 个答案:

答案 0 :(得分:3)

如果密钥不存在,或者地图为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"]++

答案 1 :(得分:1)

同样通过mapinterface{}type assertion的组合扩展JimB的答案,您可以动态创建任何复杂的结构:

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