Short Variable Declaration

The walrus operator := is a shorthand for declaring and initializing a variable in one line. It allows Go to infer the type based on the value assigned.

The Walrus Operator

// Short declaration
score := 42

// Equivalent to:
// var score int = 42

Type Inference examples

Go automatically determines the type:

  • message := "Hello" -> string
  • isGoat := true -> bool
  • pi := 3.14 -> float64

Limitations

  1. Scope: The := operator can only be used inside functions. Outside functions (at the package level), you must use the var keyword.
  2. Declaration: It must declare at least one new variable.

Same Line Declarations

You can declare multiple variables on the same line using either var or :=:

// Using walrus operator
mileage, company := 80276, "Toyota"

// Using var
var a, b, c int = 1, 2, 3