Go Constants

Go constant is a value holder whose value once assigned cannot be modified.

const keyword is used to define a constant in Go language.

A constant in go can be of any basic datatype bool, int8, int16, float32, float64, string, etc. Not all datatypes have been mentioned. But you refer Go Datatypes Tutorial.

In this tutorial, we will learn how to define constants of different data types, with examples.

Syntax

The syntax to define a constant in Go language is

</>
Copy
const name type = value

where

  • const is keyword.
  • name is the name given to this constant.
  • type is the type of value we store in this constant.
  • value is the value we would like to assign this constant with.

Specifying the type is optional for defining a constant. Go language can implicitly derive the datatype from the assigned value. But if we would like to specify the type, we may.

Boolean Constant

In the following example, we define a boolean constant and print the value to console.

Example.go

</>
Copy
package main

import "fmt"

func main() {
	const c bool = true
	fmt.Println(c)
}

Output

true

Numeric Constant

In the following example, we define a numeric constants of type int, float; and print their values to console.

Example.go

</>
Copy
package main

import "fmt"

func main() {
	const c1 int = 55
	fmt.Println(c1)

	const c2 float64 = 3.14
	fmt.Println(c2)
}

Output

55
3.14

String Constant

In the following example, we define a string constant and print the value to console.

Example.go

</>
Copy
package main

import "fmt"

func main() {
	const c = "Hello World!"
	fmt.Println(c)
}

Output

Hello World!

Conclusion

In this Golang Tutorial, we learned what a constant is in Go language, and how to define constants of various datatypes, with examples.