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"
}
A structure or struct in Golang is a user-defined type that allows to group/combine items of possibly different types into a single type. Any real-world entity which has some set of properties/fields can be represented as a struct. This concept is generally compared with the classes in object-oriented programming.
To work with a struct, you need to create an instance of it. The var keyword initializes a variable and, using dot notation, values are assigned to the struct fields. You must now create a struct type Player. Here, you have assigned the values to the struct while creating an instance ply1.
Posted on June 14, 2020. A struct can have anonymous fields as well, meaning a field having no name. The type will become the field name. In below example, string will be the field name as well type employee struct { string age int salary int }
In the Go language, you can set a struct of an array. To do so see the below code example. Where type company struct has a slice of type employee struct. Here, you can see the two different structs, and the employee struct is used as an array in the company struct.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With