SyntaxStudy
Sign Up
Go Variable Declaration and Zero Values
Go Beginner 1 min read

Variable Declaration and Zero Values

Go provides several ways to declare variables. The `var` keyword declares one or more variables with an explicit type, while the short variable declaration operator `:=` infers the type from the right-hand side expression. Both styles are idiomatic in different contexts: `var` is preferred at the package level and when the type needs to be explicit, while `:=` is common inside functions. Every type in Go has a zero value — the value a variable holds when it is declared but not explicitly initialised. Numeric types default to 0, booleans to false, strings to an empty string "", and pointers, slices, maps, channels, and functions to nil. Understanding zero values prevents a whole class of bugs that arise in languages where uninitialised variables hold garbage data. Go also supports multiple assignment, which enables idiomatic patterns such as swapping variables without a temporary: `a, b = b, a`. Functions that return multiple values — including an error — rely on this feature heavily, making error handling explicit and visible at every call site.
Example
package main

import "fmt"

func main() {
    // Explicit type with var
    var age int = 30
    var name string = "Alice"

    // Type inferred with var
    var pi = 3.14159

    // Short declaration (most common inside functions)
    city := "New York"

    // Multiple variables at once
    var x, y int = 10, 20

    // Zero values
    var zeroInt    int
    var zeroBool   bool
    var zeroString string

    fmt.Println(age, name, pi, city)
    fmt.Println(x, y)
    fmt.Printf("Zero int=%d  bool=%t  string=%q\n", zeroInt, zeroBool, zeroString)

    // Swap without a temp variable
    a, b := 1, 2
    fmt.Printf("Before swap: a=%d b=%d\n", a, b)
    a, b = b, a
    fmt.Printf("After  swap: a=%d b=%d\n", a, b)

    // Constants
    const maxRetries = 5
    const greeting  = "Hello"
    fmt.Println(greeting, maxRetries)
}