Constants in Go

Constants in Go

In this tutorial we are going to discuss about constants in Go language. A constant is anything that doesn’t change its value. In Go language, const can be either of type string, numeric, boolean, and characters. The term constant in Golang is used to denote fixed values such as

100  
"Waytoeasylearn" 
85.15

and so on.

Constants in Go

A constant can be declared using the const keyword. An important point to be noted is that the value has to be assigned while declaring a constant. It is unlike variables where we can assign value later.

Declaring a const along with specifying the type – It starts with a const keyword, followed by the name and then the type. The value must also be assigned right away, as discussed above.

const name string = "Ashok Kumar"

Declaring a const without specifying type – A const declared without type is an untyped constant. We will learn more about typed and untyped constants later on. 

For now, it’s essential to know that const declared without type has a default hidden type. The constant will be given a type once it is assigned to a variable in any way (direct initialisation, passing to a function etc.).

const name = "Ashok Kumar"

Declaring multiple const together

const ( 
   name = "Ashok Kumar"
   age = 30
   place = "Hyderabad"
)

Note

Constant Variable Cannot be reassigned after its declaration. For example below code will raise a compilation error.

package main

func main() {
	const age = 29
	age = 30
}

Output

./prog.go:5:6: cannot assign to age (declared const)

Run in playground

The constant value must be known at compile time. Hence a constant value cannot be assigned to a function call which is evaluated at run time. 

As in the below program, age is a constant, and its value should be available at compile-time, but function getValue will only be called at a run time. Hence it raises an error during compilation. 

package main

const name = "Ashok Kumar"

func main() {
	const age = getAge()
}

func getAge() int {
	return 30
}

Output

./prog.go:6:8: const initializer getAge() is not a constant

Run in playground

A constant declared within an inner having the same name as a constant declared in the outer scope will shadow the constant in the outer scope.

package main

import "fmt"

const age = 29

func main() {
	const age = 30
	fmt.Println(age)
}

Output

30

Run in playground

Typed and Untyped Constants

We are now coming to a crucial topic. In the Go language, constants are treated in a different way than any other language. GO has a very strong type system that doesn’t allow implicit conversion between any of the types. Even with the same numeric types, no operation is allowed without explicit conversion.

For example, you cannot add an int32 and int64 value. To add those, either int32 has to be explicitly converted to int64 or vice versa. However, as we will see in this tutorial, the untyped constant has the flexibility of temporary escape from the GO’s type system.

Typed Constant

A constant declared specifying the type in the declaration is a typed constant. For example, below, we are declaring a constant of type int32.

const age int32 = 30

This const a can only be assigned to a variable of type int32. If you assign it to a variable of any other type it will raise an error . For the illustration see below program.

package main

func main() {
    const age int32 = 30

    var age1 int32
    var age2 int64

    age1 = age
    age2 = age
}

Output

./prog.go:10:10: cannot use age (type int32) as type int64 in assignment

Run in playground

Untyped Constant

An untyped constant is a constant whose type has not been specified. An untyped constant in GO can be either named or unnamed. In both cases, it doesn’t have any type associated with it.

Examples of unnamed untyped constant.

1234       //Default hidden type is int
"Hello"    //Default hidden type is string
8.5        //Default hidden type is float64
true       //Default hidden type is bool
'a'        //Default hidden type is rune
3+5i       //Default hidden type is complex128

Examples of named untyped constant

const a = 1234       //Default hidden type is int
const b = "Hello"    //Default hidden type is string
const c = 8.5        //Default hidden type is float64
const d = true       //Default hidden type is bool
const e = 'a'        //Default hidden type is rune
const f = 3+5i       //Default hidden type is complex128

Untyped constant does have a default hidden type. For example, below table illustrates hidden default types for numerics, strings, characters, and boolean. Default Hidden type for Constants

Constants in Go

When you print any untyped constant using fmt.Printf it will print the default hidden type. See below program and output for both unnamed and named untyped constant.

package main

import "fmt"

func main() {
    //Unanamed untyped constant
    fmt.Printf("Type: %T Value: %v\n", 1234, 1234)
    fmt.Printf("Type: %T Value: %v\n", "Hello", "Hello")
    fmt.Printf("Type: %T Value: %v\n", 8.5, 8.5)
    fmt.Printf("Type: %T Value: %v\n", true, true)
    fmt.Printf("Type: %T Value: %v\n", 'a', 'a')
    fmt.Printf("Type: %T Value: %v\n", 3+5i, 3+5i)

    //Named untyped constant
    const a = 1234     //Default hidden type is int
    const b = "Hello"  //Default hidden type is string
    const c = 8.5      //Default hidden type is float64
    const d = true     //Default hidden type is bool
    const e = 'a'      //Default hidden type is rune
    const f = 3 + 5i   //Default hidden type is complex128

    fmt.Println("")
    fmt.Printf("Type: %T Value: %v\n", a, a)
    fmt.Printf("Type: %T Value: %v\n", b, b)
    fmt.Printf("Type: %T Value: %v\n", c, c)
    fmt.Printf("Type: %T Value: %v\n", d, d)
    fmt.Printf("Type: %T Value: %v\n", e, e)
    fmt.Printf("Type: %T Value: %v\n", f, f)
}

Output

Type: int Value: 1234
Type: string Value: Hello
Type: float64 Value: 8.5
Type: bool Value: true
Type: int32 Value: 97
Type: complex128 Value: (3+5i)

Type: int Value: 1234
Type: string Value: Hello
Type: float64 Value: 8.5
Type: bool Value: true
Type: int32 Value: 97
Type: complex128 Value: (3+5i)

Run in playground

The above program prints int32 instead of rune as rune is an alias for int32.

Now the question which comes to mind is what is the use of untyped constant. The use of an untyped constant is that the type of the constant will be decided depending upon the type of variable they are being assigned to. Sounds confusing? Let’s see with an example.

Pi constant value in math package is declared as below.

const Pi = 3.14159265358979323846264338327950288419716939937510582097494459

Notice that the type is not specified it only has a hidden default type (which is float64 here).  Let’s see a code

package main

import (
	"fmt"
	"math"
)

func main() {
	var f1 float32
	var f2 float64
	f1 = math.Pi
	f2 = math.Pi

	fmt.Printf("Type: %T Value: %v\n", math.Pi, math.Pi)
	fmt.Printf("Type: %T Value: %v\n", f1, f1)
	fmt.Printf("Type: %T Value: %v\n", f2, f2)
}

Output

Type: float64 Value: 3.141592653589793
Type: float32 Value: 3.1415927
Type: float64 Value: 3.141592653589793

Run in playground

Notice the above program.

  • When we print the type of math.Pi , it prints the default type which is float64
  • Due to the untyped nature of math.Pi constant it can be assigned to a variable of type float32 as well as float64. This is otherwise not possible in GO after the type is fixed.

Depending upon the use case, an untyped constant can be assigned to a low precision type (float32) or a high precision type(float64).

Naming Conventions

Naming conventions for constant is the same as naming conventions for variables. A constant name can only start with a letter or an underscore. It can be followed by any number of letters, numbers or underscores after that.

Global Constant

Like any other variable, a constant will be global within a package if it is declared at the top of a file outside the scope of any function. 

For example, in the below program name will be a global constant available throughout the main package in any function. Do note that the constant name will not be available outside the main package. For it to be available outside the main package, it has to start with a capital letter.

That’s all about the Constants in Go language. If you have any queries or feedback, please write us email at contact@waytoeasylearn.com. Enjoy learning, Enjoy Go language.!!

Constants in Go
Scroll to top