Understand the contract
Use var when you need an explicit type or a declaration without an initial expression. Inside a function, := declares variables and infers their types from values. Every declared variable has a value: an int starts at zero, a bool at false and a string at the empty string.
The inferred type remains fixed after declaration. In the example count is an int, so assigning a string later is a compile error. Assignment with = changes an existing variable. A short declaration needs at least one new non-blank variable in the same scope.
Work through the example
The first output is 0 false followed by an empty string. Updating count to three changes only that variable. Prefer names that describe the value, such as attempts or enabled, and keep declarations close to their first use so that their lifetime is easy to follow.
package main
import "fmt"
func main() {
var count int
var enabled bool
var name string
fmt.Println(count, enabled, name)
count = 3
message := "ready"
fmt.Println(count, message)
}Watch this boundary
A := declaration in an inner block can create a different variable with the same name. Updating it will not update the outer variable. This becomes especially easy to miss with err inside an if statement. Use = when the intention is to update a variable already in scope.
Practice with a changed input
Add a float64 variable without initialization and print it. Then shadow count inside an extra block and compare the values printed inside and outside that block.
Lesson 6 of 50
View the full Go basics seriesReferences & further reading
Need help with your Go backend?
I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.
Explore Go consulting services