As the name suggests, a constant is one that never changes. Constants in Golang are values that do not change. They are defined in a similar manner as variables but with const keyword instead of var.

A constant may be declared with a data type or without it. If it is declared without any data type, then the compiler infers its type from the value assigned to it.
Example of constant declaration follows.

package main

import "fmt"

func main() {
   // declare an int constant
   const num = 10
   // declare a string constant
   const name string = "codippa"
   fmt.Println("Integer constant is ", num)
   fmt.Println("String constant is ", name)
}

Above example shows both the ways of declaring a constant, one without a type(an int constant) and other with a type(a string constant). Output is

Integer constant is 10
String constant is codippa

A constant can be initialized only once(that is why it is called constant). Trying to change its value will make the compiler unhappy resulting in below error.

cannot assign to num

Declaring multiple constants
When declaring multiple constants, it is not required to use const keyword every time.
More than one constants can be declared using const keyword only once by declaring them on different lines and enclosing them between parenthesis. Example,

package main

import "fmt"

func main() {
   const ( num = 10
           name = "codippa" )
   fmt.Println("Type of variable is ", num)
   fmt.Print("Type of variable is", name)
}

Use of constants
Constants are used to declare values that are fixed such as flat rate of interest in a loan application, number of times a program should retry for correct user input etc.
Constants are declared to prevent the values from being changed accidentally from another file or package.

Leave a Reply