Golang constants
Introduction
In Go, a constant is an immutable value that can be used in place of a variable. Constants can be string, boolean, or numeric values. Constants cannot be declared using the :=
syntax.
How to declare a constant
Constants are declared like variables, but with the const
keyword. The :=
syntax is only used for declaring variables. This forms one of the main differences between constants and variables.
Pi
is a constant of type float64
and can be used in place of a variable.
How to declare multiple constants
To declare multiple constants, use the const
and place the variables in a parenthesis.
Here we have declared three constants of type float64
, string
, and int
.
The output of the above code is:
How to declare a constant with an explicit type
Even though constants are immutable, they can still have an explicit type. This is done by placing the type after the constant name.
The output of the above code is:
How to declare custom types as constants
The same rules apply to custom types as they do to built-in types. This means that custom types can be declared as constants.
Only custom types that are based on built-in types that can be constants can be constants.
Constant edge cases
Maps cannot be constants
Maps cannot be constants because they are mutable. This is because the length of a map is not known at compile time.
The output of the above code is:
Constant values should be known at compile time
Constant values should be known at compile time. This means that the value of a constant should be able to be determined at compile time. This includes values that are the result of a function call.
The output of the above code is:
This is because math.Pi
is a constant and can be determined at compile time.
If we were to introduce a function call, the compiler would throw an error.
The output of the above code is:
Function calls are not allowed in constants because the value of the function call cannot be determined at compile time.
Other types that cannot be used in constants are:
- Function calls
- Array and slice literals
Conclusion
In this article, we have learned how to declare constants in Go. We have also learned about some of the edge cases that can occur when declaring constants.