Skip to content
LumenaryAcademy
Foundations 50 min

Types, variables and control flow

Declarations, zero values, numbers and constants, and Go's three control structures: if, for and switch.

Code tested · 3AI-draftedAwaiting review by a computer scientist
MotivationH

Few constructs, used everywhere

Go has one loop keyword (for), one conditional (if) and one multi-way branch (switch). There is no while, no do, no ternary ?: operator. This is deliberate: when there is only one way to write a loop, every Go programmer reads every loop the same way, and code written by a colleague on another continent looks like code you wrote yourself.

The type system is similarly plain but strict. Every variable has a type fixed at compile time, the compiler infers it where it can, and nothing converts automatically: adding an int to a float64, or even an int32 to an int64, requires you to say so. That strictness catches real mistakes (a duration in seconds added to one in milliseconds, say) at the cost of a few extra characters.

Two features soften the strictness. Zero values mean that every variable starts with a sensible value (0, "", false, nil), so there is no such thing as an uninitialised variable. And untyped constants let you write x * 2 or price * 1.2 without casts, because a literal takes on whatever type the context needs.

DefinitionsH

Variables, zero values and constants

Definition— declarations

var name Type = value declares a variable; either the type or the value may be left out (if the value is omitted, the variable holds its type's zero value). Inside functions, name := value is the short form, inferring the type. const Name = value declares a constant whose value is known at compile time; a constant written without a type is untyped and takes its type from the context where it is used. In a const block, iota stands for 0, 1, 2, ... on successive lines.

go
package main

import "fmt"

// Constants can be untyped: they take a type only when used.
const Pi = 3.14159265358979

// iota counts up within a const block: a compact way to define enumerations.
type Weekday int

const (
	Monday Weekday = iota + 1
	Tuesday
	Wednesday
)

const (
	_  = iota             // skip zero
	KB = 1 << (10 * iota) // 1 << 10
	MB                    // 1 << 20
	GB                    // 1 << 30
)

func main() {
	// Three ways to declare a variable.
	var guests int = 4
	var host = "Mariam" // type inferred: string
	cups := guests + 1  // short declaration, inside functions only

	// Every type has a zero value; there are no uninitialised variables.
	var count int
	var price float64
	var name string
	var ready bool
	fmt.Printf("%d %v %q %v\n", count, price, name, ready)
	fmt.Println(host, "makes", cups, "cups")

	// Several at once, and swapping without a temporary.
	a, b := 1, 2
	a, b = b, a
	fmt.Println(a, b)

	fmt.Println(Tuesday, Wednesday, KB, MB, GB)
	var area float32 = Pi * 2 * 2 // the untyped constant becomes a float32 here
	fmt.Printf("%.4f %T\n", area, area)
}
text
0 0 "" false
Mariam makes 5 cups
2 1
2 3 1024 1048576 1073741824
12.5664 float32

Points to notice:

  • The zero values are 0 for numbers, "" for strings and false for booleans; pointers, slices, maps, channels, functions and interfaces start as nil. Idiomatic Go designs types so that the zero value is useful as it is: an empty strings.Builder or sync.Mutex is ready to use without any constructor.
  • := declares new variables and works only inside functions. At package level, use var. Mixing = and := up is a classic early mistake: = assigns to a variable that already exists.
  • a, b = b, a swaps two values. The right-hand side is evaluated completely before anything is assigned.
  • iota produces enumerations. Weekday is a new type whose underlying type is int, and Monday, Tuesday, Wednesday are 1, 2 and 3. In the second block, each line repeats the previous expression with iota one higher, giving powers of 1024. The blank identifier _ throws away the first value.
  • The untyped constant Pi became a float32 because it was used in a float32 expression. Had Pi been declared const Pi float64 = ..., assigning it to a float32 would be a compile error.
DefinitionsH

Numbers, strings and conversions

Go's basic types:

TypeNotes
int, uintthe natural size for the machine: 64 bits on all common platforms today
int8 ... int64, uint8 ... uint64fixed sizes, for file formats, protocols and hardware
byteanother name for uint8
runeanother name for int32: one Unicode code point
float32, float64IEEE 754 floating point; float64 is the default
complex64, complex128complex numbers, built in
stringan immutable sequence of bytes, by convention UTF-8 text
booltrue or false

Use int unless you have a reason not to; the standard library does.

go
package main

import (
	"fmt"
	"math"
	"strconv"
)

func main() {
	// Integer sizes: int is 64 bits on 64-bit machines; byte = uint8; rune = int32.
	fmt.Println(math.MaxInt8, math.MaxUint8, math.MaxInt)
	var level uint8 = 250
	level += 10 // overflow wraps around silently, modulo 2^8
	fmt.Println("level:", level)

	// Division truncates toward zero; % takes the sign of the left operand.
	fmt.Println(7/2, -7/2, -7%2, 7.0/2)

	// Floating point is IEEE 754, as everywhere.
	fmt.Println(0.1+0.2 == 0.3, math.Abs(0.1+0.2-0.3) < 1e-9)
	x, y := 0.1, 0.2
	fmt.Println(x+y, math.Sqrt(2), math.Inf(1))

	// Conversions are always explicit.
	n := 42
	f := float64(n) / 5
	back := int(f) // truncates toward zero
	g := -2.7
	fmt.Println(f, back, int(g))
	small := int8(n * 4) // keeps the low 8 bits: 168 becomes -88
	fmt.Println(small)

	// Numbers and text: strconv, not string(n).
	s := strconv.Itoa(n) + "!"
	parsed, err := strconv.Atoi("123")
	fmt.Println(s, parsed+1, err)
	_, err = strconv.Atoi("12x")
	fmt.Println(err)
}
text
127 255 9223372036854775807
level: 4
3 -3 -1 3.5
true true
0.30000000000000004 1.4142135623730951 +Inf
8.4 8 -2
-88
42! 124 <nil>
strconv.Atoi: parsing "12x": invalid syntax

Several of these lines deserve a pause:

  • Integer overflow wraps silently. 250 + 10 in a uint8 is 4, with no error and no panic, in every build. That is the C behaviour, chosen for speed. When overflow is possible and matters (money, sizes from untrusted input), check before you add, or use math/big for arbitrary precision.
  • Integer division truncates toward zero, so -7/2 is −3 and -7%2 is −1, exactly as in C, Java and Rust (Python differs).
  • 0.1+0.2 == 0.3 is true here, which surprises programmers from every other language. All three are untyped constants, which the compiler evaluates exactly, with arbitrary precision, before converting the result to a float64. With variables (x+y) the arithmetic happens in float64 at run time, and you get the familiar 0.30000000000000004. Compare floats computed at run time with a tolerance.
  • Conversions are explicit and written like function calls: float64(n), int(g). Converting a float to an integer truncates toward zero; converting to a smaller integer keeps the low bits (168 becomes −88 in an int8). Converting a constant that doesn't fit is a compile error: int(-2.7) with a literal is rejected, because the compiler can see the value would be lost.
  • Numbers to text go through the strconv package: Itoa and Atoi for integers, ParseFloat, FormatFloat, Quote and others. Note that Atoi returns two values, the number and an error; that pattern is the subject of lesson 6. string(65) does not produce "65" (it produces "A", the character with that code point), and go vet warns if you write it.

Note

Go has a short list of built-in functions that need no import: len and cap (sizes), append, copy, make, delete and clear (for slices and maps, lesson 4), new (allocate a variable and return a pointer to it; since Go 1.26, new(42) also sets its initial value), min and max (since Go 1.21, for any ordered values), panic and recover (lesson 6), and complex, real and imag for complex numbers. Everything else lives in a package.

Worked examplesH

if, for and switch

go
package main

import (
	"fmt"
	"strconv"
)

func classify(t int) string {
	switch {
	case t < 0:
		return "freezing"
	case t < 15:
		return "cold"
	case t < 25:
		return "mild"
	default:
		return "hot"
	}
}

func main() {
	// if can start with a short statement; its variables live only in the if/else.
	if n, err := strconv.Atoi("37"); err == nil && n > 30 {
		fmt.Println(n, "is", classify(n))
	} else if err != nil {
		fmt.Println("not a number")
	}

	// The three-part for loop.
	var evens []int
	for i := 0; i < 10; i += 2 {
		evens = append(evens, i)
	}
	fmt.Println(evens)

	// for as a while loop.
	steps, n := 0, 27
	for n != 1 {
		if n%2 == 0 {
			n /= 2
		} else {
			n = 3*n + 1
		}
		steps++
	}
	fmt.Println("Collatz steps for 27:", steps)

	// range over an integer (Go 1.22+) and over a slice.
	var squares []int
	for i := range 4 {
		squares = append(squares, i*i)
	}
	fmt.Println(squares)
	for i, t := range []int{-4, 9, 21, 33} {
		fmt.Printf("reading %d: %d is %s\n", i, t, classify(t))
	}

	// switch on a value: cases don't fall through, and can list several values.
	for _, day := range []string{"Sat", "Tue", "Fri"} {
		switch day {
		case "Sat", "Sun":
			fmt.Println(day, "weekend")
		case "Fri":
			fmt.Println(day, "almost weekend")
		default:
			fmt.Println(day, "weekday")
		}
	}

	// A labelled break leaves the outer loop.
	grid := [][]int{{3, 8, 1}, {9, 4, 7}, {2, 6, 5}}
search:
	for r, row := range grid {
		for c, v := range row {
			if v == 7 {
				fmt.Println("found 7 at", r, c)
				break search
			}
		}
	}
}
text
37 is hot
[0 2 4 6 8]
Collatz steps for 27: 111
[0 1 4 9]
reading 0: -4 is freezing
reading 1: 9 is cold
reading 2: 21 is mild
reading 3: 33 is hot
Sat weekend
Tue weekday
Fri almost weekend
found 7 at 1 2

The rules:

  • No parentheses, mandatory braces. if x > 3 { is the only form; if (x > 3) doSomething() doesn't compile. Conditions must be bool; there is no truthiness.
  • if with an init statement. if n, err := strconv.Atoi("37"); err == nil && n > 30 { runs the statement first, then tests the condition. n and err exist only inside the if and its else branches. This is the standard shape for "call something, then check its result".
  • for has four forms. The three-part C form for init; condition; post {}; the condition-only form for condition {}, which is Go's while; the bare for {}, an infinite loop ended with break or return; and for ... range, which iterates over integers (since Go 1.22), slices, arrays, strings, maps, channels and iterator functions. With a slice, range gives the index and a copy of the element; write for _, v := range s to ignore the index, or for i := range s to take only the index.
  • Each loop iteration has fresh variables (since Go 1.22). Before that, closures and goroutines started inside a loop all saw the same variable, which was a notorious source of bugs; old articles still warn about it.
  • switch cases do not fall through. Each case ends by itself, a case may list several values (case "Sat", "Sun":), and the rare explicit fallthrough keyword continues into the next case. A switch with no expression is a tidy replacement for an if/else if chain, as in classify. Cases are tested top to bottom and need not be constants.
  • Labels. break search leaves the loop labelled search; continue label works too. Go also has goto, which you will almost never need.
ExplanationH

Reading and writing control flow the Go way

Go code has a recognisable rhythm, and much of it comes from a habit experienced Go programmers call keeping the happy path on the left. Instead of nesting the main work inside conditions, a function checks for problems and returns early, so the normal case reads straight down the left margin:

go
func shippingCost(weightKg float64, country string) (float64, error) {
	if weightKg <= 0 {
		return 0, errors.New("weight must be positive")
	}
	rate, ok := ratePerKg[country]
	if !ok {
		return 0, fmt.Errorf("we don't ship to %q", country)
	}
	return weightKg * rate, nil
}

Compare a version with if weightKg > 0 { if rate, ok := ...; ok { ... } else { ... } } else { ... }: the logic is the same, but the reader has to track two levels of nesting to find the answer. Go's linters even flag an else after a return as unnecessary.

A few other habits:

  • switch true over long if chains. When three or more conditions are tested in order, an expressionless switch lines them up and makes the order visible.
  • Range loops over index loops. for i, v := range items is clearer than for i := 0; i < len(items); i++ and cannot run off the end. Use the three-part form when the step is unusual or you are not walking a collection.
  • No clever one-liners. Without a ternary operator, "pick a or b" is a four-line if/else or a small helper function. Go programmers accept the lines in exchange for code that reads the same in every file. (For the very common "smaller of two numbers", the built-in min and max functions arrived in Go 1.21.)
  • Named types for meaning. type Celsius float64 and type Weekday int cost nothing at run time, and the compiler then refuses to mix a Celsius with a plain float64 or a Weekday with a month number without an explicit conversion.
Worked examplesH

Worked example: leap years, three ways

The Gregorian calendar's rule is: a year is a leap year if it is divisible by 4, except century years, which must also be divisible by 400. So 2024 and 2000 are leap years; 1900 and 2026 are not. Here is how the rule might be written three ways in Go, and why the last is what a reviewer would ask for.

A first draft nests conditions the way the sentence is spoken:

go
func isLeap(year int) bool {
	if year%4 == 0 {
		if year%100 == 0 {
			return year%400 == 0
		}
		return true
	}
	return false
}

It is correct, but the reader has to keep two open conditions in mind. A one-line boolean expression is shorter:

go
func isLeap(year int) bool {
	return year%4 == 0 && (year%100 != 0 || year%400 == 0)
}

Many experienced Go programmers would accept this, but it takes a moment to check against the rule. An expressionless switch states each case in the order of the rule, most specific first:

go
func isLeap(year int) bool {
	switch {
	case year%400 == 0:
		return true
	case year%100 == 0:
		return false
	default:
		return year%4 == 0
	}
}

Each line can be checked against the calendar rule on its own, the order of the cases carries the meaning ("400 overrides 100, which overrides 4"), and adding a case later is a one-line change. None of the three is slower than the others in any way that matters; the compiler turns all of them into a few comparisons. The choice is about the next person who has to read the code, which in Go is always the deciding argument.

Common misconceptionsH

Common misconceptions

Misconception

"Go checks integer overflow." It doesn't, in any build mode: integer arithmetic wraps around. Only constant expressions are checked, at compile time (var b byte = 300 is an error).

Misconception

":= is just a shorter =." := declares new variables; = assigns to existing ones. Inside an inner block, x := 5 creates a new x that hides the outer one, a frequent source of "why didn't my variable change?" bugs. go vet with the shadow analyser can catch some of these.

Misconception

"string(n) turns a number into text." It turns a code point into the character it stands for: string(rune(65)) is "A". Use strconv.Itoa(n) or fmt.Sprint(n) to get "65".

Misconception

"Go's switch falls through like C's." It doesn't. Each case is self-contained; break is unnecessary at the end of a case (inside a switch, break leaves the switch, not an enclosing loop, which is why labelled breaks exist). Use fallthrough explicitly in the rare case you want it.

Exercises

Exercises

1. Types, variables and control flow

Warm-upComputational

What does fmt.Println(A, B, C) print, given this declaration?

const (
	A = iota * 10
	B
	C
)

2. Types, variables and control flow

CoreComputational

What does this print? Write the lines separated by spaces.

switch n := 2; n {
case 1:
	fmt.Println("one")
case 2:
	fmt.Println("two")
	fallthrough
case 3:
	fmt.Println("three")
case 4:
	fmt.Println("four")
}

3. Types, variables and control flow

CoreComputational

What does this print?

var lvl uint8 = 200
lvl += 100
fmt.Println(lvl)

4. Types, variables and control flow

CoreComputational

What does this print? Write the two lines separated by a space.

x := 1
if x := 5; x > 3 {
	x++
	fmt.Println(x)
}
fmt.Println(x)

5. Types, variables and control flow

StretchComputational

What does this print?

a, b := 0.1, 0.2
fmt.Println(0.1+0.2 == 0.3, a+b == 0.3)
Choose one

6. Types, variables and control flow

Warm-upComputational

What is total after this loop?

total := 0
for i := range 5 {
	if i%2 == 0 {
		continue
	}
	total += i
}

Further reading and resources