Lesson 1 · Unit 05
Structs
Group related values into one type of your own, and learn when Go copies it.
What you practise
- Declaring a struct, literals, fields, a slice of structs, a struct is copied when you assign or pass it
Try a question from this lesson
Pick one
A shop item has a name, a price and a quantity. This code makes one type that holds all three, and reads two of them back with a dot. What prints?
type Item struct {
Name string
Price int
Qty int
}
tea := Item{Name: "tea", Price: 4, Qty: 3}
fmt.Println(tea.Price * tea.Qty)Correct answer
12
Why
tea.Price is 4 and tea.Qty is 3, so the product is 12. The three values travel together as one Item, and the dot picks one out by name. No more keeping three separate variables in step.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Structs
A struct is a type you design. type Item struct { ... } lists its fields: a name and a type for each.
You make a value with a literal, naming the fields: Item{Name: "tea", Price: 4}. You read or change one field with a dot.
As before, snippets leave out package main and func main: a type or func stands on its own, and the loose lines run inside main.
type Player struct {
Name string
Score int
}
p := Player{Name: "Ada", Score: 10}
p.Score = 12 // change one field
fmt.Println(p.Name) // AdaConcept
A slice of structs
Structs go in slices like any other value: []Item is "a slice of items". Inside the braces of the slice, each item can leave out the word Item.
range hands you one item at a time, and the dot reads its fields. A slice of structs is how most programs hold their data: a list of orders, players or files.
type Item struct {
Name string
Price int
}
items := []Item{
{Name: "tea", Price: 4},
{Name: "mug", Price: 9},
}
for _, it := range items {
fmt.Println(it.Name, it.Price)
}Concept
A struct is copied
Assigning a struct copies it. So does passing it to a function: the parameter is a fresh copy, and changes to it are gone when the function returns.
That is safe, because nobody can change your value behind your back. It is also a classic bug: an update that quietly disappears. One fix is to return the changed copy and store it.
type Item struct {
Name string
Price int
}
func raise(it Item, by int) Item {
it.Price += by // changes the copy
return it // hand the copy back
}
tea := Item{Name: "tea", Price: 4}
tea = raise(tea, 2) // keep the result
fmt.Println(tea.Price) // 69 more exercises in the app
- 4× type the answer
- 1× fill the blanks
- 3× multiple choice
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.