A variable in Go stores a typed value. You declare it either with the var
keyword or, inside a function, with the short := operator. Go is statically
typed, so every variable has a type that is fixed at compile time — but you
rarely need to write that type yourself thanks to type inference.
Declaring a variable with var
The var keyword works everywhere: at package level and inside functions. You
can give the type, the value, or both.
var name string = "Ada"
var count int = 3
var ready bool // no value: ready is false
When you provide an initial value, you can drop the type and let the compiler infer it:
var name = "Ada" // inferred as string
var pi = 3.14 // inferred as float64
The short declaration operator :=
Inside a function, := declares and initialises a variable in one step. It is
the most common form in idiomatic Go.
package main
import "fmt"
func main() {
name := "Ada"
year := 1815
fmt.Printf("%s was born in %d\n", name, year)
}
Zero values
If you declare a variable without a value, Go initialises it to the zero value of its type. There are no uninitialised variables in Go.
| Type | Zero value |
|---|---|
int, float64 | 0 |
string | "" (empty string) |
bool | false |
| pointers, slices, maps | nil |
var total int // 0
var label string // ""
var enabled bool // false
A complete example
The program below declares variables in several ways and prints them. It compiles and runs as-is.
package main
import "fmt"
func main() {
// Explicit type.
var language string = "Go"
// Inferred type.
version := 1.24
// Zero value.
var stars int
stars = 42
fmt.Printf("%s %.2f has %d stars\n", language, version, stars)
}
Running it prints:
Go 1.24 has 42 stars
Common mistakes
- Declaring a variable you never use. Go refuses to compile a program with
an unused local variable. Remove it or use
_to discard a value. - Using
:=at package level. Outside a function, onlyvaris allowed. - Re-declaring with
:=. At least one variable on the left of:=must be new; otherwise use=for a plain assignment.
Practice
Declare a variable celsius set to 100, compute fahrenheit with the formula
celsius*9/5 + 32, and print 100°C = 212°F.
Show the solution
package main
import "fmt"
func main() {
celsius := 100
fahrenheit := celsius*9/5 + 32
fmt.Printf("%d°C = %d°F\n", celsius, fahrenheit)
}Because celsius is an int, the whole calculation is integer arithmetic,
which is exactly what we want here: the result is 212.
Summary
- Use
varto declare variables anywhere; use:=inside functions. - Type inference lets you omit the type when you provide a value.
- Every variable has a zero value, so nothing is ever left uninitialised.
Next, learn how to make decisions with conditionals in Go, then how to group logic into functions.