Variables in Go: A Practical Guide
Variables are one of the basic building blocks of Go programs. Understanding declaration syntax, scope, zero values, constants, and type inference helps keep code predictable and easy to maintain.
Declare Variables with var
var name string
var age intIf you do not provide an initializer, Go assigns the type’s zero value. Here, name starts as "" and age starts as 0.
You can initialize variables at declaration time:
var name = "John"
var age = 30The compiler infers the types from the values.
Short Variable Declarations
Inside functions, := provides a compact declaration form:
name := "John"
age := 30:= can only be used inside functions. Package-level declarations use var or const.
Scope
A package-level variable is visible throughout its package:
var globalVar = "I am package scoped"A variable declared inside a function or block has local scope:
func greet() {
localVar := "Hello local"
fmt.Println(localVar)
}Prefer the narrowest useful scope. Fewer package-level mutable variables generally make code easier to test and reason about.
Constants
Use const for compile-time constant values:
const Pi = 3.141592653589793Constants are not variables; they cannot be reassigned and may be untyped until used in a context that requires a concrete type.
Multiple Assignment
Go can declare or assign several values at once:
x, y := 10, 20
x, y = y, xThis makes swaps concise and is also used heavily with functions that return multiple results.
Pointers Are Separate Values
A pointer can refer to another variable:
num := 10
ptr := &num
fmt.Println(*ptr) // 10Use pointers when pointer semantics are part of the design, such as shared mutation or a meaningful nil state. Do not assume every large value automatically needs a pointer; measure performance-sensitive code.
Struct Variables
Custom struct types are ordinary variable types too:
type Person struct {
Name string
Age int
}
p := Person{Name: "Alice", Age: 25}
fmt.Println(p.Name, p.Age)Practical Guidelines
- Keep variables in the smallest useful scope.
- Prefer meaningful names over unnecessary abbreviations.
- Use constants for true compile-time constants.
- Avoid mutable package globals unless they are clearly justified.
- Let type inference reduce repetition when the type is obvious, but write explicit types when they improve an API or clarify intent.
Conclusion
Go’s variable rules are deliberately small: var, :=, const, lexical scope, static types, and predictable zero values cover most needs. Using those features intentionally leads to code that is simpler to read, test, and change.