Go Constants

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

const info string = "Welcome to Go Tutorial"

If you observe the constant 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 golang constant string example. Here, we declared a constant string using const and assigned a welcome message.

package main

import "fmt"

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

Go Constant Example

In this example, we are trying to assign the new message to the msg constant variable. As you can see, golang 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)
}
Go Constant 2

Golang Multiple Constants Declaration

We can use open and closed brackets to group or declare multiple constants. In this go example, we listed three constant 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 Constant 3