typestar

Zero values in Go

Every declared variable starts at its type's zero value: no uninitialized memory.

func zeroes() string {
    var (
        count int
        ratio float64
        name  string
        ok    bool
        items []int
        table map[string]int
        ptr   *int
    )

    items = append(items, 1) // nil slices append fine
    return fmt.Sprintf("%d %.1f %q %t %v %v %v",
        count, ratio, name, ok, items, table == nil, ptr == nil)
}

How it works

  1. Numbers start at 0, strings empty, pointers and slices nil.
  2. A nil slice appends fine, which a nil map does not.
  3. var without a value is idiomatic when the zero is what you want.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
278
Tokens
65
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 49 seconds.

Type this snippet

Step 2 of 5 in Variables & types, step 2 of 30 in Language basics.

← Previous Next →