Go · Stage 1 – Storing Information · Lesson 13 of 64

Constants

Store a named value that must not be reassigned.

Go code

const daysInWeek = 7
fmt.Println(daysInWeek)
Line-by-line explanation
  1. const creates an unchangeable named value.
  2. daysInWeek is the name.
  3. 7 is the value.
  4. Println displays it.
Expected output
7

The constant can be read like a variable.

Constants work with values the compiler can know directly, such as numbers, strings, and booleans. They are useful for facts and fixed settings in code.

Broken Go code

const daysInWeek = 7
daysInWeek = 8
Line-by-line explanation
  1. The first line creates the constant.
  2. The second line tries to reassign it.
  3. The compiler rejects the assignment.
Expected output
cannot assign to daysInWeek

The compiler protects the constant from change.