๐ŸŽ“ A1Learner
๐Ÿ”
0 of 38 lessons completed

Go Constants

A constant is a named value that never changes. Constants hold fixed values like the number of seconds in a minute.

A constant prints

const declares the constant and sets its value. The print line reads the value.

package main

import "fmt"

func main() {
	const day = "Monday"
	fmt.Println(day)
}

A constant in arithmetic

The constant holds 60. Three lots of 60 make 180.

package main

import "fmt"

func main() {
	const secondsPerMinute = 60
	fmt.Println(3 * secondsPerMinute)
}

A const block

One const word opens the block. Each line inside sets one constant.

package main

import "fmt"

func main() {
	const (
		secondsPerMinute = 60
		minutesPerHour   = 60
		hoursPerDay      = 24
	)
	fmt.Println(secondsPerMinute)
	fmt.Println(minutesPerHour)
	fmt.Println(hoursPerDay)
}

A constant cannot change

This program tries to assign a new value to a constant. The compiler refuses the program.

package main

import "fmt"

func main() {
	const limit = 10
	limit = 20
	fmt.Println(limit)
}

Example

package main

import "fmt"

func main() {
	const secondsPerMinute = 60
	fmt.Println("2 minutes:", 2*secondsPerMinute, "seconds")
	fmt.Println("5 minutes:", 5*secondsPerMinute, "seconds")
}

Key points

  • Use const to declare a constant.
  • A constant gets its value in the line that declares it.
  • A program can read a constant many times.
  • Use a const block to group constants in one place.
  • Assigning a new value to a constant fails to compile.

In this example, the constant holds 60 seconds for one minute. The first print line works out two minutes as 120 seconds. The second print line works out five minutes as 300 seconds.

Note

A constant keeps the same value for the whole run.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Go Playground

Exercise

What happens when a program assigns a new value to a constant?