Skip to main content

Go Constants

Some values should never change once they are set. For those, use the const keyword.

It declares the variable as a "constant", making it unchangeable and read-only.

Note: You have to give a constant its value at the moment you declare it.

Const Syntax syntax

main.go
const CONSTNAME type = value

Declaring a Constant

This program declares a constant in Go and prints it:

Example

Prompt
Declare a constant PI with value 3.14 and print it.
Output: Go program and captured output

Constant Rules

  • The naming rules for variables apply to constants too
  • Constants are usually named in uppercase, which makes them easy to identify and tell apart from variables
  • You can declare them inside a function or outside one

Constant Types

Constants come in two kinds:

  • Typed constants
  • Untyped constants

Typed Constants

A typed constant has its type stated in the declaration:

Example

Prompt
Declare a typed constant of type int and print it.
Output: Go program and captured output

Untyped Constants

An untyped constant leaves the type out of the declaration.

Note: The type is then inferred, meaning the compiler works it out from the constant's value.

Example

Prompt
Declare an untyped constant without specifying the type and print it.
Output: Go program and captured output

Constants: Unchangeable and Read-only

Once a constant has been declared, its value is fixed. Trying to change it later causes an error:

Example

Prompt
Show the error when trying to change the value of a constant in Go.
Output: Go program and captured output

Multiple Constants Declaration

Several constants can share one block, which keeps them easy to read:

Example

Prompt
Declare multiple constants in a block and print each one.
Output: Go program and captured output