Constants

Some values never change while a program runs, like the number of minutes in an hour. For these, write const instead of var. The name becomes a constant:

package main

import "fmt"

func main() {
	const minutesPerHour = 60
	hours := 3
	fmt.Println(hours * minutesPerHour)
}

Output:

180

You use a constant just like a variable. The difference is that its value is fixed. A constant is always declared with const and =, never with :=.

The compiler protects a constant

If any line tries to change a constant, the program does not compile:

package main

import "fmt"

func main() {
	const minutesPerHour = 60
	minutesPerHour = 90
	fmt.Println(minutesPerHour)
}

Output:

# command-line-arguments
./main.go:7:2: cannot assign to minutesPerHour (neither addressable nor a map index expression)

The message uses words you do not know yet. It means: minutesPerHour is not a variable, so you cannot store a new value in it.

Why use constants?

A constant gives a number a name. Compare these two lines:

fmt.Println(hours * 60)
fmt.Println(hours * minutesPerHour)

In the first line, a reader has to guess what 60 means. It could be minutes, seconds or a speed limit. In the second line, the name tells you. A number with no name in the middle of the code is called a magic number, and it makes code hard to read and easy to break.

To declare several constants together, put them in parentheses:

const (
	standardFee = 8
	expressFee  = 15
)
fmt.Println(standardFee, expressFee)

Output:

8 15

Constants fit the type they need

In the Operators lesson, an int variable could not be multiplied by a float64. A constant written without a type is more flexible. Go gives it the type that the calculation needs:

const fee = 12
price := 2.5
fmt.Println(price * fee)

Output:

30

fee looks like a whole number, but here it works as the float64 value 12.0, so the multiplication is allowed.

Go also works out constant calculations exactly, before the program runs. In the Basic Types lesson, adding the variables 0.1 and 0.2 printed a tiny error. With constants, there is none:

fmt.Println(0.1 + 0.2)

Output:

0.3

Numbering with iota

Sometimes you need a list of constants that are just 0, 1, 2 and so on, like sizes or days. Inside a const group, iota counts for you. It is 0 on the first line and grows by one on each line after it:

const (
	small = iota
	medium
	large
)
fmt.Println(small, medium, large)

Output:

0 1 2

A line with no value repeats the line above it, with the next iota.

Use constants for fixed facts that are part of the program. A value that comes from the user or from a file is a variable, even if it happens to stay the same during one run.

In the exercise, choose the line that declares a delivery fee that can never change.