Golang中未定义的地图元素

时间:2015-01-30 19:09:57

标签: dictionary go

出于某种原因,我收到以下错误

./execTest.go:24: template.datacenter undefined (type map[string]string has no field or method datacenter)
./execTest.go:25: template.datacenter undefined (type map[string]string has no field or method datacenter)

这是我的Go代码

package main

import (
    "fmt"
)

var template map[string]string

func main() {
    template := map[string]string{
        "cluster":    "",
        "datacenter": "The_Datacenter",
        "host":       "",
        "password":   "",
        "username":   "",
        "vm_name":    "",
    }

    args := []string{
        "--acceptAllEulas",
        "--compress=9",
    }

    if template.datacenter != "" {
        args = append(args, fmt.Sprintf("--datacenter=%s", template.datacenter))
    }

    fmt.Println(template)
}

1 个答案:

答案 0 :(得分:1)

template是地图,而不是struct。如果您想访问datacenter字符串,则需要编写template["datacenter"]

http://play.golang.org/p/M0PHGx8R8g

package main

import (
    "fmt"
)

var template map[string]string

func main() {
    template := map[string]string{
        "cluster":    "",
        "datacenter": "The_Datacenter",
        "host":       "",
        "password":   "",
        "username":   "",
        "vm_name":    "",
    }

    args := []string{
        "--acceptAllEulas",
        "--compress=9",
    }

    if template["datacenter"] != "" {
        args = append(args, fmt.Sprintf("--datacenter=%s", template["datacenter"]))
    }

    fmt.Println(template)
}