On a previous post we discussed variables in Go. We also learned what zero values are. Today we will focus on understanding what are constants in Go and how to use them.
What is a constant?
Almost every programming language has the concept of constants. Constants are variables that hold immutable values, values that you can't change when your program is running. In Go, they're declared by using the const keyword and can only hold values that the compiler knows at compile time.
Let's see some examples:
const maxAge int = 100
// declare bool const
const active = false
// declare multiple consts at the same time
const (
siteName = "Golang4us"
email = "mail@mail.com"
)
// declare a const maxRecords assigning a value to it
const maxRecords = 200 * 10
What cannot be a constant
Knowing what can be a constant is only part of the equation. The other part is knowing what cannot. Since in order to be a constant, the compiler has to know its value at compile time, anything calculated or available at runtime cannot be. And that applies to common types like arrays, slices, maps or structs.
Typed and Untyped Constants
There are two ways to declare constants in Go:
- typed: defines the type and can only be assigned to a variable of the same type
- untyped: works as a literal. Has no type but can have its type inferred by the compiler
const a name = "Adam"
// an untyped constant
const age = 42
As you may expect, although no type was specified for the variable age, the compiler will infer via its assigned value (42) that its type is int.
Checking a constant's type
When to use constants?
But when and why use constants? The rule of thumb is to use them whenever you need to reference a value that doesn't change. You could definitely hardcode constants in your code but setting them in constants in your code keeps the code DRY, making it more readable, refactorable and maintainable.