Variables

A variable is a named place in memory where your program keeps a value. You can think of it as a box with a label on it.

Declaring a variable with var

package main

import "fmt"

func main() {
	var score int = 10
	fmt.Println(score)
	score = 25
	fmt.Println(score)
}

Output:

10
25

var means "make a new variable". score is its name. int is its type, and it means the box holds a whole number. = 10 puts the first value in. The next lesson covers types.

The two lines that set score do different jobs. var score int = 10 is a declaration: it creates the box. score = 25 is an assignment: it puts a new value into a box that already exists, and the old value is gone. You declare a variable once, and after that you can assign to it as often as you like.

The short form :=

Inside a function, Go programmers usually declare variables with :=. It creates the variable and gives it a value in one step. Go works out the type from the value, so you do not write it:

name := "Alice"
age := 30
fmt.Println(name, age)

Output:

Alice 30

name is a string and age is an int, because of the values they started with. A common mistake is to use := again for a variable that already exists:

package main

import "fmt"

func main() {
	score := 10
	score := 20
	fmt.Println(score)
}

Output:

# command-line-arguments
./main.go:7:8: no new variables on left side of :=

:= only creates. To change score, write score = 20 with a plain =.

Using the old value

A variable can be on both sides of =. Go works out the right side first, using the old value, and then stores the result:

points := 10
points = points + 5
fmt.Println(points)

Output:

15

points + 5 is 15, so points becomes 15. The Operators lesson shows the other calculations you can do.

Several variables at once

var can declare several variables of the same type on one line. A variable declared without a value starts at zero:

var apples, pears int
fmt.Println(apples, pears)

Output:

0 0

Every variable must be used

Go does not allow a variable that you never use:

package main

import "fmt"

func main() {
	score := 10
	bonus := 5
	fmt.Println(score)
}

Output:

# command-line-arguments
./main.go:7:2: bonus declared and not used

This is the same idea as the unused import. An unused variable is usually a mistake: you meant to use it, or you forgot to delete it. Use it or delete it, and the program compiles.

Naming rules

A name can use letters, digits and the underscore _, but it cannot start with a digit. Upper and lower case are different, so score and Score are two variables. Go programmers write names in camelCase: the first word in lower case, and each new word starts with a capital letter, like totalPrice. Choose names that say what the value is. totalPrice is much easier to understand than x.

In the exercise, start a total at the subtotal, then give it a new value that adds the delivery fee.