Variables
Declare named values with `var` or `:=`, and learn their default values.
Use var to declare a variable with or without an explicit type. Use the shorter := form inside a function when Go can infer the type from the value. A package-level variable is declared outside any function, so it must use var.
When var has no initial value, Go gives the variable its zero value, the default for its type: 0 for numbers, false for booleans, "" for strings and nil for types such as pointers, interfaces, slices, maps, channels and functions. For a pointer, nil means it has no target; a nil slice or map behaves like an empty collection.
package main
import "fmt"
var globalCount int // zero value: 0
func main() {
var x int // 0
var s string // ""
var b bool // false
fmt.Println(x, s, b) // 0 false
fmt.Println(globalCount) // 0
}Inside a function, := declares and initialises in one step. The compiler infers the type from the right-hand side.
package main
import "fmt"
func main() {
name := "Alice" // string
age := 30 // int
active := true // bool
fmt.Println(name, age, active)
// Multiple assignment in one line
x, y := 1, 2
fmt.Println(x + y) // 3
// Swap without a temp variable
x, y = y, x
fmt.Println(x, y) // 2 1
}When declaring several related variables together, the var block form is readable and avoids repetition.
package main
import "fmt"
func main() {
var (
host = "localhost"
port = 5432
ssl = false
)
fmt.Println(host, port, ssl)
}In production
Zero values let many variables work without a separate setup step. If zero is also a meaningful value in your program, use a separate boolean to record whether the value was set. For example, default a timeout to another value only when 0 does not mean "wait forever" in your program.