Constants
This lesson discusses how constants are used to store data values in Go.
Introduction
A value that cannot be changed by the program is called a constant. This data can only be of type boolean, number (integer, float, or complex) or string.
Explicit and implicit typing
In Go, a constant can be defined using the keyword const as:
const identifier [type] = value
Here, identifier
is the name, and type
is the type of constant. Following is an example of a declaration:
const PI = 3.14159
You may have noticed that we didn’t specify the type of constant PI
here. It’s perfectly fine because the type specifier [type] is optional because the compiler can implicitly derive the type from the value. Let’s look at another example of implicit typing:
const B = "hello"
The compiler knows that the constant B
is a string by looking at its value. However, you can also write the above declaration with explicit typing as:
const B string = "hello"
Remark: There is a convention to name constant identifiers with all uppercase letters, e.g., const INCHTOCM = 2.54. This improves readability.
Typed and untyped constants
Constants declared through explicit typing are called typed constants, and constants declared through implicit typing are called untyped constants. A value derived from an untyped constant becomes typed when it is used within a context that requires a typed value. For example:
var n int
f(n + 5) // untyped numeric constant "5" becomes typed as int, because n was int.
Compilation
Constants must be evaluated at compile-time. A const can be defined as a calculation, but all the values necessary for the calculation must be available at compile time. See the case below:
const C1 = 2/3 //okay
Here, the value of c1
was available at compile time. But the following will give an error:
const C2 = getNumber() //not okay
Because the function getNumber()
can’t provide the value at compile-time. A constant’s value should be known at compile time according to the design principles where the function’s value is computed at run time. So, it will give the build error: getNumber() used as value
.
Get hands-on with 1400+ tech skills courses.