英文:
Multiple line struct definition
问题
如何使用多行定义结构体?
type Page struct {
Title string
ContentPath string
}
// 这段代码会导致语法错误
template := Page{
Title: "My Title",
ContentPath: "/some/file/path",
}
英文:
How do I define a struct using more than 1 line?
type Page struct {
Title string
ContentPath string
}
//this is giving me a syntax error
template := Page{
Title: "My Title",
ContentPath: "/some/file/path"
}
答案1
得分: 19
你需要在所有行的末尾加上逗号。
这是因为分号会自动插入。
http://golang.org/ref/spec#Semicolons
你当前的代码会变成这样:
template := Page{
Title: "My Title",
ContentPath: "/some/file/path";
};
添加逗号可以去掉错误的分号,并且在将来添加新项时不需要记得在上面添加逗号,这样更方便。
英文:
You need to end all lines with a comma.
This is because of how semicolons are auto-inserted.
http://golang.org/ref/spec#Semicolons
Your current code ends up like
template := Page{
Title: "My Title",
ContentPath: "/some/file/path";
};
Adding the comma gets rid of the incorrect semicolon, but also makes it easier to add new items in the future without having to remember to add the comma above.
答案2
得分: 10
你只是在第二个字段后面缺少一个逗号:
template := Page{
Title: "My Title",
ContentPath: "/some/file/path",
}
英文:
You're just missing a comma after the second field:
template := Page{
Title: "My Title",
ContentPath: "/some/file/path",
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论