14

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"
}
Ray
  • 2,713
  • 3
  • 29
  • 61
  • Why the downvotes for the question? Are multiline struct literals not idiomatic in Go? – Kyle Krull Mar 19 '18 at 17:11
  • Maybe because neither the question title nor the question body mentions Go. Just a tag. (That's a sincere guess; I'm not being sarcastic) – Bean Taxi Jun 22 '18 at 05:28

2 Answers2

19

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.

sberry
  • 128,281
  • 18
  • 138
  • 165
10

You're just missing a comma after the second field:

template := Page{
    Title: "My Title",
    ContentPath: "/some/file/path",
}
vvondra
  • 3,022
  • 1
  • 21
  • 34
  • Thanks, I tried it and thought it wasn't working, turns out this is the problem I'm really getting: https://stackoverflow.com/questions/14765395/why-am-i-seeing-zgotmplz-in-my-go-html-template-output – Ray Feb 27 '15 at 23:15