const keyword, followed by the constant’s name. You can optionally specify a data type (although Go can infer it if omitted) and then assign an initial value using the assignment operator.
There are two main types of constants in Go:
- Untyped Constants: These are flexible and do not have a fixed data type unless explicitly defined.
- Typed Constants: These require a specific data type, offering stronger type checking.
Untyped Constants
By default, constants in Go are untyped. This flexibility allows you to declare and initialize a constant without specifying its data type:Typed Constants
In contrast, typed constants require that you explicitly state the data type. This approach enforces stronger type checking but reduces some flexibility. For instance, creating a constant of the string data type is done as follows:Immutability of Constants
Once a constant is declared and initialized, its value cannot be changed. Attempting to alter its value will trigger a compile-time error. Consider the following example, which illustrates an error caused by trying to reassign a constant:Once set, constant values in Go are immutable. Modifying a constant will result in a compile-time error.
Duplicate Code Block Explanation
The same error is demonstrated again in the code below:Declaration Requirements
Constants must be initialized at the time of their declaration. Declaring a constant without an initial value will produce an error. For example, consider this snippet::=) cannot be used with constants. Attempting to use it will result in a syntax error:
Remember: Constants in Go must be assigned a value at the time of declaration, and the shorthand
:= is not permitted.Use Case: Calculating the Area of a Circle
Constants are especially useful in mathematical computations where certain values remain unchanged. A classic example is using the constant π (pi) to calculate the area of a circle. In the example below, we declare a globalfloat64 constant for π, compute the area of a circle using a given radius, and print the result:
That concludes our discussion on constants in Go. Understanding the distinction between untyped and typed constants, as well as their immutability and declaration requirements, is fundamental when writing reliable Go programs. For further reading, check out the Go Documentation and experiment with these concepts in your own projects for hands-on experience.