HowtoGo
Home / Basics / Variables

In Go, variables are declared explicitly. The compiler uses their declared types to catch type errors at compile time.

var declares one or more variables.

var a string = "initial"
fmt.Println(a)

Declare multiple variables of the same type in a single statement.

var b, c int = 1, 2
fmt.Println(b, c)

A variable declared without an initial value is zero-valued. The zero value for int is 0.

var e int
fmt.Println(e) // Prints 0

The := syntax declares and initializes a variable in one step. It's used inside functions only.

f := "apple"
fmt.Println(f)

The third line, 0, is e's zero value: never assigned, never nil, never undefined.

Terminal
$ go run variables.go
initial
1 2
0
apple