Mastering Constant in Golang: Declare and Use It Like a Pro

Robin
Updated on June 24, 2023

Constant provides a way to create immutable values in programming. It is useful when you want to store something in a variable that won't change later.

In Golang, a constant is a named identifier representing a fixed value. Once a constant is assigned a value, it cannot be changed or reassigned during program execution.

It is often used to define values that remain fixed throughout the program's execution, such as mathematical constants, configuration values, or flags.

There are 2 types of constants in Golang:

  • Typed Constant
  • Untyped Constant

Both of them will do the same thing only difference is how we declare them. Let's learn about constants in Golang – how to create them and how to create multiple constants in a block.

Declaring (Creating) Typed Constant in Golang

When you declare a typed constant in Go, you are specifying the data type of the constant explicitly. This helps ensure type safety and clarity in your code.

To declare a typed constant, you use the const keyword followed by the constant name, its type, and the assigned value.

This is the syntax:

          const constantName type = value
        

For example, let's say you want to declare a constant called maxValue with the type int and assign it the value of 100. Here's how you would do it in Golang.

          const maxValue int = 100
        

In this example, const is the keyword that indicates you're declaring a constant. The maxValue is the name you've chosen for the constant.

The int is the type of constant, which is explicitly specified. And finally, 100 is the value assigned to the maxValue constant.

Once you've declared the typed constant, you can use it in your code just like any other variable of that type. For instance, you can assign the constant value to a variable, use it in mathematical operations, or print its value.

          package main

import "fmt"

func main() {
	const maxValue int = 100
	var currentValue int = 50

	fmt.Println("The maximum value is:", maxValue)
	fmt.Println("The current value is:", currentValue)

	// You can perform operations with the constant
	var newValue int = currentValue + maxValue
	fmt.Println("The new value is:", newValue)
}

        

In this example, we declare the maxValue constant with a type of int and assign it the value 100. Now you can print this constant to the console like a normal variable.

You can also perform mathematical operations with other variables like adding maxValue and currentValue, and store the result in the newValue variable.

          package main

import "fmt"

func main() {
	const (
		Pi             = 3.14159
		Radius         = 5.0
		SquareSide     = 10
		TriangleBase   = 6
		TriangleHeight = 8
		CircleArea     = Pi * Radius * Radius
	)

	fmt.Println("The area of the circle is:", CircleArea)
	fmt.Println("The perimeter of the square is:", SquareSide*4)
	fmt.Println("The area of the triangle is:", 0.5*TriangleBase*TriangleHeight)
}
        

In this code snippet, we utilize the declared constants within the main function to calculate and print the area of the circle, the perimeter of the square, and the area of the triangle.

Also Read: Understanding All Data Types in Golang: A Complete Guide


Declaring Untyped Constant in Golang

When you declare an untyped constant in Go, you don't explicitly specify its type. Instead, the type of the constant is determined based on the value assigned to it.

This allows for more flexibility in using the constant in different contexts. To declare an untyped constant, you use the const keyword followed by the constant name and the assigned value.

This is the syntax:

          const constantName = value
        

For example, let's say you want to declare an untyped constant called pi and assign it the value of 3.14159. Here's how you would do it in Golang.

          const pi = 3.14159
        

In this pi constant, we are not explicitly setting the type. That's why it is known as an untyped constant. The compiler will determine its type based on the value.

In this case, the compiler will infer the type of pi constant as float64 because the value is a decimal.

Also Read: Golang Variable: Different Ways to Create Variables in Golang


Differences Between Typed and UnTyped Constants

There are some differences between typed and untyped constants in Golang even though both of them will store fixed values:

Typed ConstantsUntyped Constants
DeclarationExplicitly declared typeInferred type based on assigned value
Type SafetyEnsures type safetyAllows implicit conversions to compatible types
Type ConversionRequires explicit type conversionsImplicitly converts to compatible types
ExpressionsRetains specific types of expressionsAdapts to the type of operations or assignments
Compiler ChecksSubject to type checks by the Go compilerNo explicit type checks performed
FlexibilityLess flexible in terms of type adaptabilityMore flexible, can be used with different types implicitly

These differences highlight how typed constants provide strict type checking and preserve their specific type throughout expressions, while untyped constants offer flexibility and implicit conversions based on context.

The choice between typed and untyped constants depends on the desired level of type safety and the specific requirements of your code.


How to Declare Multiple Constants in a Block

In Go, you have the option to declare multiple constants within a single block using the const keyword. This approach allows you to group related constants together to improve code organization and readability.

To declare multiple constants in a block, you use the following syntax:

          const (
    constant1 = value1
    constant2 = value2
    constant3 = value3
    // more constants...
)
        

Let's say you want to declare a block of constants related to geometric shapes. You can declare them within a single block using the const keyword.

          const (
    Pi         = 3.14159
    Radius     = 5.0
    SquareSide = 10
    TriangleBase   = 6
    TriangleHeight = 8
    CircleArea = Pi * Radius * Radius
)
        

In this example, we declare multiple constants within a block. By organizing these related constants within a block, it becomes easier to manage and understand their purpose in the code.


Naming Conventions for Golang Constants

Using capital letters for constants is the naming convention in most programming languages. But in Golang, if you start the name of a variable with a capital letter, it automatically gets exported from the package.

Therefore, if you don't want to expose your constants from your package, you must start the name with a small letter.

We often use camelCase for naming variables in Golang. For example: firstName, lastName etc. You can also use the same style for constant names.

But if you want to name your constants differently to identify the difference between a normal variable and a constant, you can use the underscore ( _ ) symbol. For example: max_value, total_amount, etc.

It's totally up to you how you want to name your constants. Golang doesn't have any fixed rules for naming variables, constants, or functions. But it is good practice to use the same style throughout the entire application to improve code readability and maintainability.


Differences Between Constants and Variables in Golang

Constants and variables are used to store and manage values in Go. But they have some important differences you should remember.

  • Use Cases: Constants are commonly used to represent fixed values that won't change. Variables, on the other hand, are used to store and manage data that can change during program execution.
  • Immutability: Constants store fixed values. You can't change or assign a new value to it once defined. On the other hand, variables can be assigned different values at different points in your code.
  • Declaration and Initialization: When you declare a constant, you must assign a value to it right away. Variables, however, can be declared without an initial value and assigned a value later in your code.
  • Compiler Evaluations: Constants are evaluated at compile-time, which means their values are known and substituted in the code during compilation. Variables, on the other hand, are evaluated at runtime when the program is running.
  • Memory Allocation: Constants are usually not allocated memory at runtime because they are directly replaced with their values during compilation. Variables, however, require memory allocation to store their values.
  • Performance Implications: Constants can provide performance benefits in certain situations. Since the compiler knows their values at compile time. On the other hand, variables may have slight overhead due to runtime memory allocation and the potential for value changes.

Understanding these differences between constants and variables helps you choose the appropriate approach based on whether you need a value to be constant or subject to change throughout your program.


How Golang Constant is Different Than Other Languages

Most programming languages have the option to create constants. Golang treats constant values differently. Because the Golang compiler evaluates them at the compile time.

This means that the compiler analyzes and calculates the values of constants during the compilation phase of your program and replaces those constants with their values.

          package main

import "fmt"

func main() {
    const maxValue = 100
    const initialValue = maxValue / 2

    fmt.Println("Initial value:", initialValue)
    fmt.Println("Double the initial value:", initialValue*2)
}
        

In this example, we have two constants: maxValue and initialValue. maxValue is set to 100, and initialValue is calculated by dividing maxValue by 2.

During the compilation phase, the Go compiler will replace initialValue with the result of 100 / 2, which is 50, before executing the program.

The important point to note here is that the compiler performs the division operation maxValue / 2 during compilation, not at runtime. Therefore, this calculation is performed once during compilation, and the compiled code contains the value 50 directly.


Conclusion

By declaring constants, you can ensure that specific values remain fixed throughout your program. This immutability of constants prevents accidental modifications and helps maintain data stability.

You have seen how you can declare constants in your Go application. You also have learned the differences between typed and untyped constants.

If you need to create multiple constants which are related to each other, you can declare them in a block. It will help you to organize and maintain your code.

Related Posts