英文:
Assigning map of slices in a struct in Golang
问题
在Golang中,正确地将切片的映射分配给结构体的方法如下:
package main
import (
"fmt"
)
type Test struct {
name string
testCase map[string][]string
}
func main() {
t := Test{
name: "myTest",
testCase: map[string][]string{
"key": {"value1", "value2"},
},
}
fmt.Println(t)
}
你的代码有一个语法错误,是因为在testCase
的映射中,缺少了逗号。我已经帮你修复了这个问题。请使用上述修复后的代码重新尝试。
英文:
How to correctly assign a map of slices to a struct in Golang?
I tried to following, but it does not work:
package main
import (
"fmt"
)
type Test struct {
name string
testCase map[string][]string
}
var t = Test{
name: "myTest",
testCase: map[string][]string{"key": {"value1", "value2"}}
}
func main() {
fmt.Println(t)
}
.\main.go:14:61: syntax error: unexpected newline, expecting comma or }
答案1
得分: 1
你在分配值时必须将其类型作为前缀添加。
type Test struct {
name string
testCase map[string][]string
}
var t = Test{
name: "myTest",
testCase: map[string][]string{
"key": {"value1", "value2"},
},
}
不要忘记在项的末尾添加逗号分隔符,因为它使用垂直样式的映射
英文:
You have to add its type as a prefix when you assign the value.
type Test struct {
name string
testCase map[string][]string
}
var t = Test{
name: "myTest",
testCase: map[string][]string{
"key": {"value1", "value2"},
},
}
> Don't forget to add comma separator at the end of the item, since its
> use vertical style map
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论