Go by Example

Variables

var declarations, short variable declaration :=, zero values, and multiple assignment.

Go has two ways to declare variables: the var keyword (explicit type, works anywhere) and the short variable declaration := (inferred type, inside functions only). Both are valid - use var at package scope or when you want to name the type explicitly; use := inside functions for brevity.

var declares a variable with an explicit or inferred type. When no initial value is given, the variable is set to its zero value - 0 for numbers, false for booleans, "" for strings, and nil for pointers, slices, maps, channels, and functions.

package main
 
import "fmt"
 
var globalCount int // zero value: 0
 
func main() {
    var x int         // 0
    var s string      // ""
    var b bool        // false
 
    fmt.Println(x, s, b)  // 0  false
    fmt.Println(globalCount) // 0
}

Inside a function, := declares and initialises in one step. The compiler infers the type from the right-hand side.

package main
 
import "fmt"
 
func main() {
    name := "Alice"   // string
    age := 30         // int
    active := true    // bool
 
    fmt.Println(name, age, active)
 
    // Multiple assignment in one line
    x, y := 1, 2
    fmt.Println(x + y) // 3
 
    // Swap without a temp variable
    x, y = y, x
    fmt.Println(x, y)  // 2 1
}

When declaring several related variables together, the var block form is readable and avoids repetition.

package main
 
import "fmt"
 
func main() {
    var (
        host = "localhost"
        port = 5432
        ssl  = false
    )
    fmt.Println(host, port, ssl)
}

In production

Zero values are a deliberate design feature, not an oversight. A struct field you forget to initialise is not a nil panic - it's a predictable zero. This makes Go programs more robust by default, but it also means that "is this value set?" requires a sentinel or a separate boolean flag, not a nil check. Know your types' zero values before adding defensive nil checks that paper over bad initialisation. The pattern if cfg.Timeout == 0 { cfg.Timeout = defaultTimeout } is idiomatic Go.

Enjoyed this? Get more essays on software craft delivered to your inbox.

Subscribe free