A constant variable is a type of variable whose value is fixed. This means that once a constant variable is declared, we cannot change later it in the program. If other parts of the program attempt to change the value, the compiler returns a runtime panic.
Constants are very useful when you have a critical variable that would resulting into errors or incorrect values if changed.
This article covers how to declare and use constant variables in the Go programming language.
How to Declare a Constant Variable?
In Go, we declare a constant variable as we normally would a normal variable. However, we include the keyword const at the beginning of the variable name.
The syntax is as shown:
NOTE: You cannot declare a constant variable using the := syntax.
The example below declares a constant variable called PI:
import "fmt"
func main() {
const PI = 3.14159
fmt.Println(PI)[cc]
}
The above creates a constant variable PI and assigns it a value.
You can have a constant variable of any valid data type as:
const hello = "Hello" // string
const boolean = false // bool
Golang Group of Constants
Go also allows to create a group of constant values. For example:
import "fmt"
func main() {
const (
PI = 3.14159
i = 10
hello = "Hello"
boolean = false
)
fmt.Println(PI)
fmt.Println(i)
fmt.Println(hello)
fmt.Println(boolean)
}
The code above should print all the constant variables as shown in the output below:
10
Hello
false
We keep talking about constant values. What happens when we try to assign a value to a constant variable?
An example is as shown below:
func main() {
const (
PI = 3.14159
)
PI = 3.141
}
The compiler will return an error as shown:
Note the value of a constant variable must be known before compilation. This means, you cannot assign the result of an expression to a const value.
For example:
import (
"fmt"
"math"
)
func main() {
const myvar = math.Sqrt(64)
fmt.Println(myvar)
}
The code above returns an error as:
Typed Constants
We know Go is a strongly typed language. Hence, we can create a typed constant by specifying its type during declaration.
For example:
The above creates a typed constant.
Keep in mind that once you declare a typed constant, you cannot use assign it a variable of similar type.
Untyped Constants
If you declare a constant variable without defining its type, you create an untyped constant. For example:
const i = 100 //untyped int
const b = true //untyped bool
Conclusion
Using this article, you learned the fundamentals of working with constant variables in the Go programming language.