Variables, constants, and zeros

Declaration, short assignment, and what Go puts in memory when you did not set a value.

A variable can be declared explicitly or in the short form:

var count int
name := "Tropa"

:= requires at least one new name on the left. That is why people write err := do(), and on the next line already err = doAgain(). If you write := where every name on the left is already declared in this block, the code will not build. If at least one name is new, := declares it and also assigns the old ones. That makes it easy to shadow an outer variable:

err := load()
if err := validate(); err != nil {
    return err
}
// внешний err здесь не тот, что внутри if

The inner err is a different variable. The outer load error has not gone anywhere, and it is easy to lose. Shadowing is an ordinary Middle mistake, not a rare curiosity.

Every type has a zero value. A variable with no explicit literal receives it: 0 for numbers, false for bool, "" for a string, nil for pointers, slices, maps, channels, interfaces, and functions. You can rely on zero. var ready bool is already false. A separate = false adds nothing.

A constant must be computed at compile time. You cannot store the result of a call to time.Now() in it. An iota group numbers constants from zero:

const (
    A = iota // 0
    B        // 1
    _
    C        // 3
)

Skipping a line also increments iota. A hole in the enumeration is a deliberate gesture, not junk.

Why a Middle developer cares

The zero value is part of the API. A good type tries to be useful at zero: bytes.Buffer, a mutex, an empty slice in range. If the zero value of your structs is dangerous (for example, a client with no address), say so with a New constructor, not with a comment that says "do not forget to call Init".

Practice

  1. Short declaration

    Inside the function there is already a variable err. Which line declares a new variable n and assigns a new value to err?

    • err := read()
    • n, err := read()
    • n := err = read()
    • var n, err := read()
  2. Zero values

    What is var s []int immediately after the declaration?

    • An empty non-nil slice of length 0
    • A nil slice
    • A slice of a single zero
    • The code will not compile without a literal
  3. iota

    What are the constants A, B, and C equal to?

    const (
        A = iota
        B
        _
        C
    )
    

    Write three numbers separated by spaces, in the order A B C.