Go by Example: Variables
Learn the various ways to declare and initialize variables in Go. This example covers the standard `var` keyword, type inference, multiple variable declarations, zero values, and the concise short declaration syntax `:=`, providing a complete overview of variable management in Go.
Code
package main
import "fmt"
func main() {
// var declares 1 or more variables
var a = "initial"
fmt.Println(a)
// Declare multiple variables at once
var b, c int = 1, 2
fmt.Println(b, c)
// Go infers the type automatically
var d = true
fmt.Println(d)
// Variables without initialization get zero values
var e int
fmt.Println(e)
// := is shorthand for declare and initialize
f := "apple"
fmt.Println(f)
}Explanation
Go offers two primary ways to declare variables: the explicit var keyword and the short declaration operator :=. The var keyword provides clear type specification and works at both package and function levels, while := offers concise syntax for local variables with type inference.
Variables declared with var without explicit initialization automatically receive zero values—a critical safety feature that eliminates the entire class of "uninitialized variable" bugs common in languages like C and C++. This guarantees that every variable has a well-defined value before use. Zero values are: 0 for numeric types, false for booleans, "" (empty string) for strings, and nil for pointers, slices, maps, channels, functions, and interfaces.
The short declaration operator := combines declaration and initialization in a single, concise statement. It's the preferred method for local variables inside functions when the type is obvious from the right-hand side. However, := can only be used inside functions—package-level variables must use var. Multiple variables can be declared and assigned simultaneously using either syntax.
Best practices for variable declaration:
:=for local variables when type is clear from contextvarwith explicit type annotation when clarity trumps concisenessvarat package level since:=isn't allowed there- Multiple declaration (
a, b := 1, 2) for related variables - Rely on zero values instead of explicit initialization to default values

