Bitpath

Boss lesson · Unit 01

Structs and methods

Build a small inventory from structs, pointers and methods.

13 exercisesabout 3 min

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?

Go
type Item struct {
  Name string
  Qty  int
}

a := Item{Name: "pen", Qty: 3}
b := a
b.Qty = 0
fmt.Println(a.Qty, b.Qty)

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".

Go
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) // 12

Concept

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).

Go
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 5

10 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.

One email when Bitpath is ready to try. Nothing else. Privacy