Go Variables
A variable is a named place in memory that holds a value. Go is statically typed: every variable has a type that is fixed at compile time. But you rarely have to write the type yourself, because Go can infer it from the value.
Two ways to declare a variable
| Syntax | Where it works | Type |
|---|---|---|
var name type = value |
anywhere (inside and outside functions) | written or inferred |
name := value |
only inside functions | always inferred |
package main
import "fmt"
func main() {
var city string = "Lisbon" // type written explicitly
var population = 545000 // type inferred: int
temperature := 21.5 // short declaration, type float64
fmt.Println(city, population, temperature)
}Lisbon 545000 21.5
The := operator is called the short variable declaration. It is the most common form inside functions. Outside functions (at package level) every declaration must start with a keyword, so you must use var.
Zero values
A variable declared without a value is not "undefined" or garbage — it gets the zero value of its type.
package main
import "fmt"
func main() {
var count int
var price float64
var name string
var ready bool
fmt.Println(count, price, ready)
fmt.Printf("name is %q\n", name)
}0 0 false
name is ""
| Type | Zero value |
|---|---|
int, float64 and other numbers |
0 |
string |
"" (empty string) |
bool |
false |
| pointers, slices, maps, channels, functions, interfaces | nil |
Declaring several variables at once
You can declare multiple variables in one line, or group declarations in a var ( ... ) block.
package main
import "fmt"
var (
appName = "Notes"
version = 3
)
func main() {
var x, y int = 10, 20
first, last := "Ada", "Lovelace"
a, b := 1, "mixed types are fine"
fmt.Println(appName, version)
fmt.Println(x+y, first, last)
fmt.Println(a, b)
}Notes 3
30 Ada Lovelace
1 mixed types are fine
Assignment and swapping
Once a variable exists, use plain = to change it. Go evaluates the whole right side first, so swapping two values needs no temporary variable.
package main
import "fmt"
func main() {
left, right := "apple", "banana"
left, right = right, left // swap
counter := 1
counter = counter + 4
fmt.Println(left, right, counter)
}banana apple 5
:= needs at least one new variable on the left side. Writing counter := 2 a second time in the same scope is an error: no new variables on left side of :=.
Unused variables are errors
A local variable that is declared but never used stops compilation:
package main
import "fmt"
func main() {
total := 100
fmt.Println("hello")
}# command-line-arguments
./example.go:6:2: declared and not used: total
If you need to ignore a value, assign it to the blank identifier _, which accepts anything and throws it away.
Naming rules
- Must start with a letter or underscore; can contain letters, digits and underscores.
- Case-sensitive:
ageandAgeare different variables. - Cannot be a keyword such as
funcorrange. - Go style prefers short names for short scopes (
i,n,err) and camelCase for longer ones (maxRetries).
Tip: Use
:=inside functions andvarwhen you want the zero value (var total int) or need to state a type explicitly (var ratio float64 = 1).
Test yourself
What is the zero value of a string variable?
nil"0"""(empty string)- It is undefined
Where can the short declaration x := 5 NOT be used?
- Inside
main - Inside an
ifstatement - At package level, outside any function
- Inside a
forloop
What happens when you declare a local variable and never use it?
- It is a compile error
- A warning is printed
- It is removed silently
- It causes a runtime panic