Skip to main content
A short variable declaration uses the := operator to declare and initialize one or more local variables simultaneously, relying on the compiler to infer their types from the assigned values. It serves as a syntactic shorthand for a standard var declaration with an initializer, omitting the explicit type signature.

Syntax

Lexical Scope Restrictions

Short variable declarations are strictly confined to block scope. They can only be utilized within the body of a function. Package-level variables must be declared using the var keyword; attempting to use := at the package level results in a compile-time syntax error (non-declaration statement outside function body).

Type Inference Mechanics

The compiler resolves the type of the newly declared variable at compile time based on the right-hand side (RHS) expression.
  • If the RHS is a typed expression, the variable inherits that exact type.
  • If the RHS is an untyped constant, the variable assumes the default type for that constant class: int for integers, float64 for floating-point numbers, complex128 for complex numbers, rune for character literals, string for string literals, and bool for boolean constants.

Redeclaration and Assignment Rules

Unlike standard var declarations, the := operator permits the redeclaration of existing variables within the same lexical block, subject to a strict condition: at least one non-blank variable on the left-hand side (LHS) must be newly declared. The blank identifier (_) does not satisfy the requirement for a new variable. When this condition is met, the := operator acts as a standard assignment for the previously declared variables and a declaration for the new ones. The redeclared variables must retain their original type.

Variable Shadowing

Because := always constitutes a declaration (for at least the new variables on the LHS), using it within a nested lexical block—such as an if, for, or switch statement—will instantiate a new variable. This new variable will shadow any variable with the identical identifier in an outer scope for the duration of the inner block.
Tired of Poor Go Skills? Fix That With Deep Grasping!Learn More