var is the full declaration and works at package level and inside functions, while :=, the short variable declaration, works only inside functions. With var you can name the type and skip the value, and the variable then holds its zero value. := always needs a value and infers the type from it. At package level you must use var.
Inside a function, := can also redeclare a variable, as long as at least one name on its left is new. Redeclaring assigns to the existing variable. That is why val, err := f() can appear after err already exists.
One trap is := inside an inner block, which creates a new variable that shadows the outer one instead of assigning to it.
// Package level - must use var
var globalVar string
func main() {
// Both are valid inside functions
var localVar string // Zero value: ""
shortVar := "hello" // Type inferred as string
fmt.Println(globalVar, localVar, shortVar)
}
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
The diagram below the answer is the concept . Jump to it ↓