01 / 08

Explain the difference between := and var declarations in Go.

var works at both package and function scope with explicit typing, while := is a shorthand only valid inside functions that infers the type from the assigned value.

Key differences
  1. 1

    var x int — works at package or function scope, allows explicit type, sets zero value if no initializer

  2. 2

    x := 5 — only valid inside functions, infers type, requires an initial value

  3. 3

    := can declare multiple variables at once: x, err := someFunc()

  4. 4

    := allows re-declaration if at least one variable on the left is new

  5. 5

    var is preferred for package-level variables and when zero value initialization is intentional

var vs := examples

Common pitfall: := inside an inner scope shadows the outer variable rather than updating it. This causes subtle bugs especially with the error variable. Always check if := is creating a new variable or shadowing an existing one.