Go Tutorial · Go Basics · Lesson 4 of 30

Go Variables

Declare variables with var and :=, zero values and multiple assignment.

Declaring variables

Example 1
package main

import "fmt"

func main() {
	var city string = "Berlin"
	var population = 3_850_000 // type inferred: int
	country := "Germany"       // short declaration
	population += 1000
	fmt.Println(city, country, population)
}

Output

Berlin Germany 3851000

Run this on your computer — see “Get Started” for setup.

  • var name type = value — the full form; the type can be left out when there's a value.
  • name := value — short declaration, inside functions only. It's the most common form.

Zero values

Variables declared without a value get their type's zero value — there's no "uninitialised" state:

Example 2
package main

import "fmt"

func main() {
	var count int
	var price float64
	var name string
	var ready bool
	var items []string
	fmt.Printf("%d %v %q %v %v %v\n", count, price, name, ready, items, items == nil)
}

Output

0 0 "" false [] true

Run this on your computer — see “Get Started” for setup.

Multiple assignment

Example 3
package main

import "fmt"

func main() {
	x, y := 1, 2
	x, y = y, x // swap
	fmt.Println(x, y)
	var (
		host = "localhost"
		port = 8080
	)
	fmt.Printf("%s:%d\n", host, port)
}

Output

2 1
localhost:8080

Run this on your computer — see “Get Started” for setup.

Test yourself

What is the zero value of a string in Go?

  1. nil
  2. "" (empty string)
  3. "0"
  4. undefined
Show answer

Answer: "" (empty string)