Variables: var vs :=
Go has two ways to declare a variable. The long form, var name type = value, works everywhere and lets you leave out either the type or the value. The short declaration name := value declares and assigns in one step, infers the type from the value, and is only allowed inside functions. Most Go code uses := inside functions and var at package level or when you want the zero value.
package main
import "fmt"
var appName = "inventory" // package level: var only
func main() {
var count int = 3 // explicit type and value
var price = 9.99 // type inferred: float64
var ready bool // no value: gets the zero value, false
sku := "A-100" // short declaration, type string
x, y := 10, 20 // several at once
x, y = y, x // swap, no temp variable needed
fmt.Println(appName, count, price, ready, sku)
fmt.Println(x, y)
}inventory 3 9.99 false A-100
20 10Declare var discount float64 without a value and print it. What does it print, and why?
| Form | Where allowed | Use it when |
|---|---|---|
var x int | Anywhere | You want the zero value, or you declare now and assign later |
var x = 5 | Anywhere | Package-level variables |
var x int64 = 5 | Anywhere | The inferred type would be wrong (5 alone would be int) |
x := 5 | Inside functions only | The normal case inside a function |
declared and not used
package main
import "fmt"
func main() {
name := "Gopher"
age := 12
fmt.Println(name)
}# command-line-arguments
./main.go:7:2: declared and not used: ageLike unused imports, an unused local variable is a compile error in Go, not a warning. A variable you assign and never read is usually a bug — a typo, or a result you forgot to check. (Unused package-level variables are allowed.)
Use the variable, delete it, or — if you must keep the assignment for now — assign it to the blank identifier: _ = age.
package main
import "fmt"
func main() {
name := "Gopher"
age := 12
fmt.Println(name, age)
}no new variables on left side of :=
package main
import "fmt"
func main() {
x := 1
x := 2
fmt.Println(x)
}# command-line-arguments
./main.go:7:4: no new variables on left side of :=:= means "declare". x already exists in this scope, so the second line declares nothing. With several names on the left, := is allowed as long as at least one is new — that is why n, err := ... twice in a row works when n is new.
Use plain assignment = to change an existing variable.
package main
import "fmt"
func main() {
x := 1
x = 2
fmt.Println(x)
}