Constants in Golang

Constants, like variables, store some data, but unlike variables, the values of constants cannot be changed, they are set once. Constants are evaluated at compile time. This reduces the amount of work that needs to be done during execution, and simplifies the search for errors, constant-related (since some of them can be detected at compile time).

Define a Constant

To define constants, use the const keyword:

const name string = "Mead"

And unlike a variable, we can't change the value of a constant. And if we try to do this, we will get an error when compiling:

const name string = "Mead"
name = "techieclues" // Error

In a single definition, you can declare several constants at once:

const {
name string = "techieclues"
description string = "learn Golang"

Or we can also write it like this:

const name, description = "techieclues" , "learn Golang"

Constants Initialization

At the same time, it is imperative to initialize the constant with an initial value when declaring it. For example, the following constant definitions are invalid because they are not initialized:

const name
description string

If you define a sequence of constants, you can omit initialization with a value for all constants except the first constant. In this case, the constant has no value and gets the value of the previous constant:

package main
import "fmt"
func main() {
    const {
        name = "Docker"
        name4 = "Kubernetes"
    fmt.Println(name, name2, name3, name4, name5)

The output will be:

Docker Docker Docker Kubernetes Kubernetes

Note: Constants can only be initialized with constant values, such as numbers or strings, or values of other constants. But we can't initialize a constant with a variable value.