Go by Example

Variables

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

Two common variable declaration forms are var (explicit or inferred type, usable anywhere) and the short variable declaration := (inferred type, inside functions only). 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, interfaces, 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. An uninitialised struct field receives its type's zero value; that value can be nil for pointer, interface, slice, map, channel, and function fields, so using a nil pointer can still panic. If zero means "unset" in your application, use a sentinel or a separate flag. A default such as if cfg.Timeout == 0 { cfg.Timeout = defaultTimeout } is appropriate when zero has no separate meaning.

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