Go Constants

Constants in Golang programming are the variable whose values remain fixed. Once we declared this variable and assigned a value, we could not change it later. In this Programming, we can declare a constant variable using the const keyword. For instance, 

const info string = "Welcome to Go Tutorial"

If you observe the declaration, it is the same as the variable declaration. We replaced the var keyword with const. We can declare a constant without a data type.

const num = 200

It is a simple string example. Here, we declared a string using const and assigned a welcome message.

package main

import "fmt"

func main()  {
    const msg string = "Welcome to Go Tutorial"
    fmt.Println(msg)
}
Example 1

Go Constant Example

In this example, we are trying to assign the new message to the msg variable. As you can see, the const program is throwing an error.

package main

import "fmt"

func main()  {
    const msg string = "Welcome to Go Tutorial"
    fmt.Println(msg)

    msg = "New Message"
    fmt.Println(msg)
}
Example 2

Golang Multiple Constants Declaration

We can use open and closed brackets to group or declare multiple const. In this example, we listed three variables and then performed some arithmetic operations on them.

package main

import "fmt"

func main()  {
    const (
        x = "Hi"
        y = "Hello"
        z = 2
    )
    fmt.Println(x)
    fmt.Println(y)
    fmt.Println(z)
    fmt.Println(x + y)
    fmt.Println(z * 2)
}
Golang Multiple Constants Declaration 3