Theory

What a struct is

At the end of last lesson we spotted a signal: title, pages, read travel together everywhere. Go has a name for that — a struct: several fields joined into one new type.

// Item is one record of the list.
type Item struct {
	Title string
	Pages int
	Read  bool
}

Read it as: "from now on a type Item exists; every value of it has a text Title, a number Pages and a flag Read." Notice the fields start with a capital letter — why that matters you will see in lesson 10, when we save records to a file.

How this changes your life:

  • One parameter instead of three. formatItem(it Item) instead of formatItem(title string, pages int, read bool).
  • Impossible to mix up the order. Before, formatItem(pages, title, ...) was at best a compile error; now the fields have names.
  • A record = one value. Later the whole list is just []Item — a shelf of records (lesson 7).

A struct is your first own type. string and int came with the language; Item you defined yourself, for your theme.