Boss lesson · Unit 01
Structs and methods
Build a small inventory from structs, pointers and methods.
What you practise
- Struct types and literals, pointers without arithmetic, value against pointer receivers, a small inventory program built from them
Try a question from this lesson
Pick one
You are building a shop inventory. In Python, b = a would give one object two names. What does this Go program print?
type Item struct {
Name string
Qty int
}
a := Item{Name: "pen", Qty: 3}
b := a
b.Qty = 0
fmt.Println(a.Qty, b.Qty)Correct answer
3 0
Why
A struct is a value, like an array: b := a copies every field, and b is a separate item from then on. Nothing is shared unless you ask for it with a pointer. This is the opposite of a Python object.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Structs and pointers
A struct groups named fields. Item{Name: "pen"} builds one, and any field you leave out gets its zero value.
&a is a pointer to a: its address, with the type *Item. Assigning through a pointer changes the original. Field access looks the same either way: p.Qty works on a pointer without any ->.
There is no pointer arithmetic. A pointer only means "this one, not a copy".
type Item struct {
Name string
Qty int
}
a := Item{Name: "pen"} // Qty is 0
p := &a // p is a *Item
p.Qty = 12
fmt.Println(a.Qty) // 12Concept
Methods have receivers
A method is a function with a receiver in front of its name: func (it Item) Empty() bool. You call it as pen.Empty(). Any named type can have methods; there are no classes.
The receiver is passed like any argument. A value receiver (it Item) gets a copy. A pointer receiver (it *Item) gets the address and can change the original. Go takes the address for you: pen.Add(5) means (&pen).Add(5).
type Item struct{ Qty int }
func (it Item) Empty() bool {
return it.Qty == 0
}
func (it *Item) Add(n int) {
it.Qty += n
}
pen := Item{}
pen.Add(5)
fmt.Println(pen.Empty(), pen.Qty)
// false 510 more exercises in the app
- 2× fill the blanks
- 3× multiple choice
- 1× order the lines
- 1× true or false
- 2× type the answer
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.