多行结构定义

huangapple go评论100阅读模式
英文:

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",
}

huangapple
  • 本文由 发表于 2015年2月28日 07:07:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/28775878.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定