In Go, variables can be declared using either the var keyword or the short variable declaration operator :=. While both serve to create variables, they differ in syntax, scope, and usage context.
Using var
The var keyword is the standard way to declare variables and works in all scopes—both global and local.
// Declare a variable without initialization (zero value is used)
var count int
// Declare and initialize with explicit type
var name string = "Go"
// Declare multiple variables of the same type
var x, y, z int = 1, 2, 3
// Type inference: omit the type, let Go infer from the value
var a, b = true, 3.14
Using := (Short Variable Declaration)
The := syntax is a shorthand that combines declaration and initialization. It infers types from the right-hand side and is more concise.
// Short declaration inside a function
count := 42
message, length := "hello", len("hello")
However, := has a critical restriction: it can only be used inside functions (i.e., in local scope). Attempting to use it at package level results in a compilation error.
Additionally, := requires at least one new variable on the left-hand side. This means you cannot redeclare all existing variables using := in the same scope unless at least one is new:
func example() {
x := 10
y := 20
// x, y := 30, 40 // ❌ Error: no new variables
x, z := 30, 40 // ✅ OK: z is new
}
Key Differences
- Scope:
varworks globally and locally;:=is local-only. - Syntax:
varsupports optional type annotation;:=always infers types. - Redeclaration:
:=allows redeclaration only if at least one variable is new in the current scope.
As a best practice, use var for package-level variables and := for concise local declarations within functions.