var vs :=
tally needs somewhere to keep things: the file name, the list of words, a running total. Go gives you two ways to declare a variable, and knowing which one fits saves you a surprising number of compile errors.
The rule
varworks everywhere and allows a bare type;:=is function-only and needs a new name.
var is the full form. You can give a type, a value, or both:
var minLength = 3 // type inferred: int
var total int // no value: starts at 0
var path string = "notes.txt"It works at package level (outside any function) and inside functions. A group of them can share one block:
var (
minLength = 3
verbose = false
):=, the short declaration, declares and assigns in one step and infers the type from the value:
func main() {
path := "notes.txt"
words, err := readWords(path)
// ... use words and err
}Its rules:
- It only works inside functions. At package level it is a syntax error.
- It must declare at least one new variable on the left.
total := 0twice in the same block fails with "no new variables on left side of :=". - With several names, the new ones are declared and the existing ones are simply assigned. That is why
a, err := f()followed byb, err := g()is fine:bis new,erris reused.
Plain = never declares; it only assigns to a variable that already exists.
And one rule for both: a local variable you declare but never use is a compile error.
The shortcut
Ask two questions in order: Am I outside a function? Use var. Do I have a starting value? Use :=. If not, var name Type makes the "starts empty" intent obvious.
Package-level setting
minLengthsits outside every function, so it must bevar minLength = 3.
The trap: writing total := 0 again later in the same block to "reset" it. Use total = 0.
Drills
Answer fast — trust the rule.
Which line is a compile error at package level, outside any function?
Inside one block you write count := 1 and then count := 2. What happens?
n, err := parse(a) then, in the same block, m, err := parse(b). Is the second line legal?
What is the type of x after x := 7.0?
Remember
varworks everywhere and allows a bare type;:=is function-only and needs a new name.- Shortcut: outside a function →
var; have a value →:=; want "starts empty" →var name Type. - Trap:
:=twice in one block; plain=is how you change a value.
