Learn/Go/2. Values and variables
Lesson 2 of 15
Sign in

Go, lesson 2

Values and variables

A variable is a named box that holds a value. In Go every variable has a type, and the type never changes. A variable that holds a whole number can never later hold text. The compiler checks this for you before the program runs.

Basic types

These are the types you will use most:

TypeHoldsExample
intwhole numbers42, -7
float64numbers with a fraction3.75
stringtext

2 exercises to try what you just read.

Exercise 1

Swap the scores

Press Ctrl Enter or Check to test your code.

Exercise 2

Fruit stand total

Press Ctrl Enter or Check to test your code.

"hello"
booltrue or falsetrue

There are also sized integers such as int64 and uint8, but plain int is the right default.

Declaring variables

The long form uses var, the name, then the type:

Go can usually work out the type from the value, so you can leave it off:

Inside a function, the most common form is the short declaration :=. It declares and assigns in one step:

After a variable exists, change it with plain =. Using := again for the same name in the same block is an error, because := always means "make a new variable".

You can declare several at once, and even swap two values in a single line:

Zero values

If you declare a variable without a value, Go fills in its zero value: 0 for numbers, "" for strings and false for bools. There is no "uninitialised" garbage in Go.

Unused variables are errors

Go refuses to compile a function that declares a local variable and never reads it. This catches typos and leftover code early. If you really need to ignore a value, assign it to the blank identifier _.

Constants

A constant is a value fixed when the program is compiled. Declare it with const. You cannot assign to it later.

Numeric constants are flexible: const Pi = 3.14159 has no fixed type until you use it, so it works with both int and float64 expressions where that makes sense.

Converting between types

Go never converts types silently. Adding an int to a float64 is a compile error. Convert explicitly by writing the type name like a function:

Naming

Names start with a letter and use camelCase (highScore, maxSpeed). Short names are fine for short-lived values like loop counters. A name that starts with a capital letter is exported, meaning other packages can see it; that matters later when you build packages.

To see a value's type while learning, use the %T verb: fmt.Printf("%T\n", 2.5) prints float64. To print a float with a fixed number of decimals, put the count after a dot: fmt.Printf("%.2f\n", 3.5) prints 3.50.

Further reading

  • A Tour of Go: Variables
  • A Tour of Go: Basic types and zero values
  • A Tour of Go: Constants

The starter declares two scores. Swap their values using one multiple assignment, then print them on one line separated by a space. Do not just print the numbers in the other order; change the variables.

Expected output:

A fruit stand sells pears. Declare a constant PricePerPear with the value 0.75, an int variable pears set to 6, and compute the total as a float64. Print these three lines (use %T for the type line and %.2f for two decimals):

var lives int = 3
var player string = "Mira"
var speed = 2.5 // float64
score := 0          // int
name := "Mira"      // string
ready := true       // bool
score = score + 10
x, y := 1, 2
x, y = y, x // now x is 2 and y is 1
var count int     // 0
var label string  // ""
var done bool     // false
const MaxPlayers = 4
const Greeting = "Welcome!"
apples := 7
price := 0.5
total := float64(apples) * price // 3.5
whole := int(3.99)              // 3 (the fraction is dropped)
red 12 blue 30
pears: 6
total: 4.50
type of total: float64