Lesson 4 / 26

Variables, Constants and Zero Values

Every type has a useful default.

var, :=, const

Declare variables with var name type or, inside functions, the short form name := value, which infers the type. Variables declared without a value get their type's zero value: 0 for numbers, "" for strings, false for booleans, nil for pointers, slices, maps, channels and interfaces, and a struct with all fields zeroed. Constants (const) are fixed at compile time and can be untyped. Designing types whose zero value is useful (like sync.Mutex or bytes.Buffer) is idiomatic Go.

Types, control flow, functions, collections

Go's basics are small but have important details: zero values, multiple returns, and slice aliasing.

Four ideas: variables and zero values, control flow, functions, slices and maps.
Figure 2.1 — Variables, control flow, functions and collections.

Zero values and type inference, run

I ran this with Go 1.27.1 (go run . in a module named demo, standard library only). Uninitialised variables hold zero values; the struct prints with %+v showing field names, and its nil slice is still usable. %T shows inferred types.

package main

import "fmt"

type User struct {
	Name   string
	Age    int
	Active bool
	Tags   []string
}

const MaxRetries = 3 // untyped constant

func main() {
	var count int
	var price float64
	var label string
	var u User
	fmt.Printf("int=%d float=%v string=%q\n", count, price, label)
	fmt.Printf("struct=%+v tags-nil=%v\n", u, u.Tags == nil)
	city := "Pune" // short declaration infers the type
	fmt.Printf("%T %T %d\n", city, 2.5, MaxRetries)
}

Output:

int=0 float=0 string=""
struct={Name: Age:0 Active:false Tags:[]} tags-nil=true
string float64 3

Prefer := inside functions

The short form is idiomatic for local variables; use var when you want the zero value or an explicit type.

Quick check: What is the zero value of a string in Go?

  • nil
  • The empty string ""
  • "0"
  • undefined
Answer

The empty string "" — Every type has a defined zero value.