Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple line struct definition

Tags:

go

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"
}
like image 838
Ray Avatar asked Feb 27 '15 23:02

Ray


People also ask

How do you define a struct in Golang?

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.

How to make struct in Go?

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.

What is anonymous fields in Go struct?

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 }

How do you create an array of structs in Golang?

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.


1 Answers

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.

like image 159
sberry Avatar answered Sep 30 '22 01:09

sberry