Tutorials References Exercises Menu
Paid Courses

Go Constants


Go Constants

If you do not want others (or yourself) to override existing variable values, you can use the const keyword.

The const keyword declares the variable as "constant", which means unchangeable and read-only.

Syntax

const VARIABLE type = value

Note: The value of a constant must be assigned when you declare it.


Constant Rules

  • Constant names follow the same rules as variable names
  • Constant names are usually written in uppercase letters (for easy identification and differentiation from variables)
  • Constants can be declared both inside and outside of a function

Constant Types

There are two types of constants:

  • Typed constants
  • Untyped constants

Typed Constants

Typed constants are declared with a defined type:

Example

package main
import ("fmt")

const A int = 1

func main() {
  fmt.Println(A)
}
Try it Yourself »

Untyped Constants

Untyped constants are declared without a type:

Example

package main
import ("fmt")

const A = 1

func main() {
  fmt.Println(A)
}
Try it Yourself »

Note: In this case, the type of the constant is inferred from the value (means the compiler decides the type of the constant, based on the value).


Constants: Unchangeable and Read-only

When a constant is declared, it is not possible to change the value later:

Example

package main
import ("fmt")

func main() {
  const A = 1
  A = 2
  fmt.Println(A)
}

Result:

./prog.go:8:7: cannot assign to A
Try it Yourself »

Multiple Constants Declaration

Multiple constants can be grouped together into a block for readability:

Example

package main
import ("fmt")

const (
  A int = 1
  B = 3.14
  C = "Hi!"
)

func main() {
  fmt.Println(A)
  fmt.Println(B)
  fmt.Println(C)
}
Try it Yourself »