One dish at Bimo's Meatball Stall has several details at once: name, price, and spicy or not. If every detail sits in its own variable, then by the time the menu has ten dishes, you have thirty variables that are easy to mix up.
A struct groups those related values into one, each with its own name and type. Think of a menu card: every card has the same columns, the struct is the card template, and each dish is one card filled in. It's like an object in JavaScript, except the columns are set in advance through a type, and you can't just add more.
Defining a struct
type Menu struct {
Name string
Price int
Spicy bool
}
type Menu struct { ... }makes a new type calledMenu. It's written outsidefunc main, usually above it.- Every line inside it is a field: its name, then its type.
- Fields that start with a capital letter (
Name,Price) can be used from other packages,encoding/jsonincluded. Lowercase fields are only visible inside their own package.
Making a struct value
meatballs := Menu{Name: "Tendon Meatballs", Price: 15, Spicy: true}
tea := Menu{Name: "Iced Tea", Price: 5}
var empty Menu
fmt.Println(meatballs) // {Tendon Meatballs 15 true}
fmt.Println(tea) // {Iced Tea 5 false}
fmt.Println(empty) // { 0 false}
Menu{Name: ..., Price: ...}is called a struct literal: the type name, then curly braces holdingField: value. So fortype Person struct { Name string; Age int }, a value is writtenp := Person{Name: "Budi", Age: 25}.- A field you don't mention gets its zero value:
tea.Spicyisfalse. var empty Menugives every field its zero value:"",0,false. An empty string doesn't show, which is why it prints{ 0 false}.- You can leave out the field names,
Menu{"Chicken Noodles", 12, false}, but then every field is required, in exactly the right order. Miss one and Go refuses withtoo few values in struct literal of type Menu. Field names are safer. - A field the type doesn't have is refused too:
Menu{Stock: 20}fails withunknown field Stock in struct literal of type Menu.
Read, change and print fields
fmt.Println(meatballs.Name, meatballs.Price) // Tendon Meatballs 15
fmt.Printf("%v\n", meatballs) // {Tendon Meatballs 15 true}
fmt.Printf("%+v\n", meatballs) // {Name:Tendon Meatballs Price:15 Spicy:true}
fmt.Printf("%#v\n", meatballs) // main.Menu{Name:"Tendon Meatballs", Price:15, Spicy:true}
meatballs.Price = 16
fmt.Println(meatballs.Price) // 16
meatballs.Namereads one field;meatballs.Price = 16changes it.%vprints just the values, the same asfmt.Println.%+vadds the field names, the most useful one when hunting a bug.%#vprints it like Go code, with the type name and quotes.
A struct is a value: copied whole
meatballs := Menu{Name: "Tendon Meatballs", Price: 15, Spicy: true}
copied := meatballs
copied.Price = 18
fmt.Println(meatballs.Price, copied.Price) // 15 18
copied := meatballs copies every field into a new struct, just like an array and unlike a slice. So meatballs.Price stays 15.
A struct as a function parameter
func printMenu(m Menu) {
fmt.Printf("\"%s\": $%d\n", m.Name, m.Price)
}
func raisePrice(m Menu) {
m.Price = 20 // only changes this function's own copy
}
printMenu(meatballs) // "Tendon Meatballs": $15
printMenu(tea) // "Iced Tea": $5
raisePrice(meatballs)
fmt.Println(meatballs.Price) // 15
func printMenu(m Menu)is a function that takes oneMenuvalue and calls itm(functions in detail come in the next lesson). Because it prints from the fields,m.Nameandm.Price, it's right for any dish.\"inside text prints a quote mark, and%sand%dare replaced by the string and number values in order.- A struct sent to a function is copied too.
raisePricechanges its copy, notmeatballs. How to change the original (a pointer) comes in the Method lesson.
A struct inside a struct, and anonymous structs
type Order struct {
Menu Menu
Portions int
}
order := Order{Menu: tea, Portions: 2}
fmt.Printf("%+v\n", order) // {Menu:{Name:Iced Tea Price:5 Spicy:false} Portions:2}
fmt.Println(order.Menu.Name, order.Portions*order.Menu.Price) // Iced Tea 10
guest := struct {
Name string
Table int
}{Name: "Sari", Table: 3}
fmt.Printf("%+v\n", guest) // {Name:Sari Table:3}
- A field may have another struct as its type. The dots chain on:
order.Menu.Name. guestis an anonymous struct: a struct defined on the spot without giving the type a name. Handy for one-off data. When the shape is used again and again, make atype.
💡 Field tags for JSON
type MenuJSON struct {
Name string `json:"name"`
Price int `json:"price"`
Spicy bool `json:"spicy,omitempty"`
stock int
}
b, _ := json.Marshal(MenuJSON{Name: "Iced Tea", Price: 5, stock: 20})
fmt.Println(string(b)) // {"name":"Iced Tea","price":5}
- The text in backticks after the type is called a tag. Go itself doesn't use it, but packages such as
encoding/jsonread it. json:"name"names the key in the JSON.omitemptyskips a field holding its zero value, so aspicyoffalsedoesn't appear.stockis lowercase, soencoding/jsoncan't see it at all.json.Marshalreturns two values, the result and an error._throws the error away (covered in the Multiple Return lesson).
⚠️ Copies, literals without field names, and fields missing from JSON
- Thinking a change to a copy changes the original. Assigning and function parameters copy the struct.
- Struct literals without field names. As soon as the type gets a new field, every positional literal breaks. Use
Field: value. - Lowercase fields vanish from JSON. Start with a capital letter when the field must be seen from another package.
- Typed-in text inside the function. A function that takes a struct must print from its fields, not finished text, so it's right for any value.
TL;DR: type Menu struct { Name string; Price int } makes a type with named fields. A value is made with a struct literal Menu{Name: "Tendon Meatballs", Price: 15}, fields you don't mention hold their zero value, and var m Menu is all zero values. m.Name reads and changes a field. %v prints the values, %+v with field names, %#v like Go code. A struct is a value: assigning and function parameters make a copy. An anonymous struct is a struct with no type name, and tags such as json:"name" are read by other packages.
⚡ A menu card template
Write:
type Menu struct {
Name string
Price int
Spicy bool
}
Meaning: type Menu struct makes a new type. Every line is a field: its name, then its type. Fields that start with a capital letter can be used from other packages.
⚡ A struct literal
Write:
meatballs := Menu{Name: "Tendon Meatballs", Price: 15, Spicy: true}
fmt.Println(meatballs.Name) // Tendon Meatballs
Meaning: The type name, then curly braces holding Field: value. A field you don't mention holds its zero value, and meatballs.Price = 16 changes one field.
⚡ A struct is copied whole
Guess first: copied := meatballs, then copied.Price = 18. What is meatballs.Price now?
Still 15. A struct is a value, so copied := meatballs copies every field. A function parameter gets a copy too.
Meaning: A struct is copied like an array, unlike a slice.
⚡ A struct with no type name
Write:
guest := struct {
Name string
Table int
}{Name: "Sari", Table: 3}
Meaning: This is an anonymous struct: a struct defined and used on the spot without a type name. Handy for one-off data. When the shape is used again and again, make a type.