Bitpath

Boss lesson · Unit 05

An inventory

A shop's stock as a slice of structs, changed safely through methods.

13 exercisesabout 3 min

What you practise

  • Items as structs, stock changed through methods, totals and a report, the copy that silently loses an update

Try a question from this lesson

Pick one

A shop keeps its stock in a program. Each item has a name, a price in cents and a stock count, and the whole inventory is a slice of them. What prints?

Go
type Item struct {
  Name  string
  Price int // cents
  Stock int
}

inv := []Item{
  {"tea", 450, 3},
  {"mug", 900, 0},
}
fmt.Println(len(inv), inv[0].Stock)

The idea

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

The plan

The inventory needs three things.

Data: an Item struct, kept in a slice.

Questions: methods that only read, such as Value(): price times stock.

Changes: methods that update an item, such as Remove(n). They take a pointer receiver, and they return an error when the change is not allowed, so stock can never go below zero.

Go
type Item struct {
  Name  string
  Price int // cents
  Stock int
}

func (it Item) Value() int {
  return it.Price * it.Stock
}

tea := Item{"tea", 450, 3}
fmt.Println(tea.Value()) // 1350

11 more exercises in the app

  • 4× type the answer
  • 2× fill the blanks
  • 3× multiple choice
  • 1× order the lines
  • 1× true or false

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