英文:
Undefined map element in Golang
问题
由于某种原因,我得到了以下错误:
./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)
}
英文:
For some reason I am getting the error below
./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)
Here is my Go code
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
得分: 2
template
是一个映射(map),而不是一个结构体(struct)。如果你想访问 datacenter
字符串,你需要写成 template["datacenter"]
。
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)
}
你可以在这里查看代码:http://play.golang.org/p/M0PHGx8R8g
英文:
template
is a map, not a struct
. If you want to access the datacenter
string you need to write 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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论