๐ŸŽ“ A1Learner
๐Ÿ”

Go Variables

A variable is a named place that stores a value. A program can read the value and change it later.

Declare, assign, and print

The word string is the type. A type says what kind of value a variable holds.

package main

import "fmt"

func main() {
	var name string
	name = "Hana"
	fmt.Println(name)
}

A short declaration

The := form declares and sets a value at once. Go reads the type from the value.

package main

import "fmt"

func main() {
	city := "Seattle"
	fmt.Println(city)
}

Two variables on one line

One var line declares both variables. A later line changes only the second value.

package main

import "fmt"

func main() {
	var first, second int = 3, 4
	second = 10
	fmt.Println(first, second)
}

Zero values

No line sets a value for these variables. Printf shows the zero value of each type.

package main

import "fmt"

func main() {
	var count int
	var name string
	var ready bool
	fmt.Printf("[%d][%s][%t]", count, name, ready)
}

A variable must be used

This program declares a variable and never uses it. The compiler refuses the program.

package main

import "fmt"

func main() {
	score := 90
	fmt.Println("Game over")
}

Example

package main

import "fmt"

func main() {
	name := "Hana"
	level := 3
	fmt.Println("Name:", name)
	fmt.Println("Level:", level)
}

Key points

  • Use var to declare a variable.
  • A var line names a type for the variable.
  • Assign a value with the = sign.
  • Use := to declare a variable and set its value in one line.
  • Go reads the type from the value in a := line.
  • One line can declare two variables of the same type.
  • A variable with no set value holds the zero value of its type.

In this example, the first line sets name to Hana with a short declaration. The second line sets level to 3. The two print lines show each value beside its label.

Note

Every declared variable must be used in the program.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Go Playground

Exercise

Which line declares a variable and sets its value at once?