← Fundamentals
Fundamentals

Go zero values and short declarations

Can the stock register open, reject a bad import and count rentals without a setup call?

Check what Go initializes automatically and which operations that state supports.

Outcome

Predict the zero value of any variable or field, tell which zero values are usable and which panic, separate a missing key from a stored 0, say which names a := declares, and keep a struct’s zero value ready to use.

Terminology (5)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Zero value
The value a variable or field holds before the program assigns one: 0, "", false, or nil, and for a struct, each field’s zero value.
Nil map
A map variable’s zero value. Reads give the value type’s zero and len is 0, but a write panics.
Comma ok
The two-result form of a lookup, v, ok := m[k], where ok reports whether the key is present.
Short variable declaration
name := value. It declares each new name on its left in the current block and assigns those already declared there.
Value receiver
A method receiver declared without *: the method gets a copy of the struct.

Starting state and declared names

A Go variable declared without an explicit initializer receives its type’s zero value. A struct’s fields each receive theirs. That guarantees an initial state, but whether the state is useful depends on the operation: reading, appending and storing can require different preparation.

A short declaration with := also determines which names belong to the current block. Distinguish a newly declared local from an update to an existing binding, then follow whether a method receives the caller’s value or a copy. These decisions determine which state survives for the next caller.

01Zero values

Open the register before stock arrives

The tool shed needs a register that can open before any stock arrives. A tool with none left must still appear as stocked, and a rejected quantity import must report its first bad line without printing a partial stock list. Check the register’s initial state before connecting those reports to a rental ledger that callers can declare with var.

Before adding tools, the register checks its count, label and Shed fields. It then tries to record the first saw. Predict which operations complete on the declared values.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import "fmt"

type Shed struct {
	Name  string
	Tools map[string]int
}

func main() {
	var count int
	var label string
	var shed Shed

	fmt.Printf("%d %q %q %t\n", count, label, shed.Name, shed.Tools == nil)
	fmt.Println(len(shed.Tools), shed.Tools["saw"])

	shed.Tools["saw"] = 1

	fmt.Println("stored")
}
What does go run print?
Go · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
go run main.go

Use the Go setup from the first reading. Each file is a complete main.go; predict its output, then run go run main.go. The lesson and all three repairs use Go.

02Missing keys

Keep an out-of-stock tool on the report

The shed stocks ladders, but none are left. It has never stocked anvils. The first line reads their quantities; the second asks whether each name is present. Predict both lines before choosing how to report them.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import "fmt"

func main() {
	stock := map[string]int{"saw": 2, "ladder": 0}

	fmt.Println(stock["ladder"], stock["anvil"])

	_, stocked := stock["ladder"]
	_, known := stock["anvil"]
	fmt.Println(stocked, known)
}
What are the two printed lines?

03Short declarations

Follow the conversion error back to the caller

This small conversion probe skips a bad field and totals the rest. The importer will need a stricter policy, but first check which err the loop writes: predict the total and whether the outer err is still nil.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import (
	"fmt"
	"strconv"
)

func main() {
	total := 0
	var err error

	for _, field := range []string{"2", "x", "3"} {
		n, err := strconv.Atoi(field)

		if err != nil {
			continue
		}

		total += n
	}

	fmt.Println(total, err == nil)
}
What is printed?

04Value receivers

Check what two rental calls leave behind

The rental probe starts with an initialized map. Add increments a total and records a tool name, then returns. Predict what main sees after two calls to the same tally.

main.go
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
package main

import "fmt"

type Tally struct {
	total int
	seen  map[string]bool
}

func (t Tally) Add(name string) {
	t.total++
	t.seen[name] = true
}

func main() {
	tally := Tally{seen: map[string]bool{}}

	tally.Add("saw")
	tally.Add("drill")

	fmt.Println(tally.total, len(tally.seen))
}
What is printed?

05Repair the tool shed

Stock reports, quantity parsing, then a rental ledger

Repair three paths through the register. The stock report must retain stocked tools at 0. The importer must report its first bad quantity and suppress the partial stock list. The rental caller must be able to use a ledger declared with var.

This lab is Go-only. Each file contains its imports, reader and complete caller.

Repair the tool shed

Use each supplied caller to check the report, the rejected import and the accumulated rentals.

  1. easy · F-ZERO-V4-1 Report what the shed stocks
  2. medium · F-ZERO-V4-2 Stop on a bad quantity
  3. hard · F-ZERO-V4-3 Count rentals from a zero ledger
Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.