Drills

Drills — variables and values

Variables have to be used, not just read about. Five short drills. We don't have functions yet (those are the next lesson), so each is a few lines you write inside main — declare, assign, print. Type each one, run it, then compare with the solution. Try it before you peek.

1 (easy) — pick the right form. Declare three things: an app name that never changes, a mutable counter starting at 0, and a price 9.99. Choose const, := or var for each.

const appName = "Book list" // never changes → const
count := 0                  // will change → := (inferred int)
price := 9.99               // := (inferred float64)
fmt.Println(appName, count, price)
Book list 0 9.99

2 (easy) — zero values. Declare qty (int), active (bool) and label (string) with var and no value, then print all three. What comes out?

var qty int
var active bool
var label string
fmt.Printf("[%d] [%v] [%s]\n", qty, active, label)
[0] [false] []

The [] at the end isn't a bug — a zero-value string is "", empty text. The brackets make that visible.

3 (medium) — declare now, assign later. Sometimes you don't know a value yet. Declare title empty, then assign "Dune" on a later line, then print it. (This is the one case where var beats :=.)

var title string   // "" for now
title = "Dune"     // fill it in later
fmt.Println(title) // Dune

4 (medium) — spot the bug. This does not compile. Why, and what's the smallest fix?

const pages = 380
pages = 412 // ← error here
fmt.Println(pages)

A const can never be reassigned — that's the whole point of const. If the value must change, it isn't a constant; make it a var:

var pages = 380
pages = 412
fmt.Println(pages) // 412

5 (harder) — swap two variables. You have a := 1 and b := 2. Make a hold 2 and b hold 1. Many languages need a temporary variable; Go can do it in one line with multiple assignment.

a, b := 1, 2
a, b = b, a
fmt.Println(a, b) // 2 1

The right side b, a is fully evaluated first, then both are assigned — so no temporary variable is needed.

Tip. Put all five in one main, run it, and match every line against the expected output. Getting comfortable with the three declaration forms now will save you from a hundred small confusions later.