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
main.go
package main
import ("fmt")
const PI = 3.14
func main() {
fmt.Println(PI)
}
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
main.go
package main
import ("fmt")
const A int = 1
func main() {
fmt.Println(A)
}
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
main.go
package main
import ("fmt")
const A = 1
func main() {
fmt.Println(A)
}
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
main.go
package main
import ("fmt")
func main() {
const A = 1
A = 2
fmt.Println(A)
}
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
main.go
package main
import ("fmt")
const (
A int = 1
B = 3.14
C = "Hi!"
)
func main() {
fmt.Println(A)
fmt.Println(B)
fmt.Println(C)
}