Go > Variables and Constants > Declaration and Initialization > Constant declaration (const)

Constant Declaration in Go

This example demonstrates how to declare and use constants in Go. Constants are immutable values that are known at compile time. They are useful for defining values that should not change during the program's execution, such as mathematical constants, configuration parameters, or error codes.

Basic Constant Declaration

This code snippet showcases the fundamental way to declare constants in Go using the const keyword. We declare three constants: Pi (a float64), MagicNumber (an integer), and Greeting (a string). Notice that the type of the constant is explicitly defined. Constants must be assigned a value at compile time and their value cannot be changed later during the program's execution.

package main

import "fmt"

const Pi float64 = 3.14159
const MagicNumber int = 42
const Greeting string = "Hello, world!"

func main() {
	fmt.Println("Pi:", Pi)
	fmt.Println("Magic Number:", MagicNumber)
	fmt.Println("Greeting:", Greeting)
}

Untyped Constants

Go supports untyped constants. When you declare a constant without explicitly specifying its type, the compiler infers the type based on the value assigned to it. These constants behave as if they have the best possible precision. Untyped constants can be implicitly converted to different types when used, providing flexibility. In the example, UntypedInt and UntypedFloat are untyped constants. When assigned to variables of type int and float64, they are implicitly converted.

package main

import "fmt"

const UntypedInt = 10
const UntypedFloat = 3.14

func main() {
	fmt.Printf("Type of UntypedInt: %T\n", UntypedInt)
	fmt.Printf("Type of UntypedFloat: %T\n", UntypedFloat)

	var x int = UntypedInt  // Implicit conversion to int
	var y float64 = UntypedInt // Implicit conversion to float64
	var z float64 = UntypedFloat

	fmt.Println("x:", x)
	fmt.Println("y:", y)
	fmt.Println("z:", z)

}

Constant Expressions

Constants can also be defined using constant expressions. Constant expressions are evaluated at compile time. This example demonstrates how to define constants related to computer memory sizes (KB, MB, GB) using constant expressions. The values are calculated at compile time, making the program more efficient. Constants can be grouped using parentheses for better readability.

package main

import "fmt"

const ( // Grouped declaration
	KB = 1024
	MB = KB * 1024
	GB = MB * 1024
)

func main() {
	fmt.Println("KB:", KB)
	fmt.Println("MB:", MB)
	fmt.Println("GB:", GB)
}

Real-Life Use Case

Constants are commonly used to define configuration parameters for an application. For example, API endpoints, database connection strings, or default values for settings. By using constants, you ensure that these values are not accidentally modified during runtime.

Best Practices

  • Use descriptive names for constants to improve code readability.
  • Group related constants together using parentheses.
  • Use constants for values that should not change during the program's execution.
  • Consider using untyped constants for greater flexibility, especially for numeric literals.

Interview Tip

A common interview question is to explain the difference between constants and variables in Go. Constants are immutable and their values are known at compile time, while variables can be modified during runtime. Constants are declared using the const keyword, while variables are declared using the var keyword.

When to use them

Use constants when you have values that are known at compile time and should not be changed during the program's execution. This improves code readability, maintainability, and safety.

Memory footprint

Constants do not consume runtime memory. Their values are embedded directly into the compiled code. Therefore, using constants generally leads to more efficient programs.

Alternatives

If a value needs to be changed during program execution, a variable must be used instead of a constant. There are no direct alternatives to constants if immutability is required.

Pros

  • Immutability: Guarantees that the value will not change during runtime.
  • Compile-time Evaluation: Constant expressions are evaluated at compile time, improving efficiency.
  • Readability: Using named constants improves code readability and maintainability.

Cons

  • Limited Flexibility: Constants must be known at compile time, so they cannot be used for values that are determined at runtime.

FAQ

  • What happens if I try to change a constant's value?

    The Go compiler will produce an error if you attempt to modify the value of a constant after it has been declared. This is because constants are immutable and their values are fixed at compile time.
  • Can I declare a constant without assigning a value?

    No, you must assign a value to a constant when you declare it. Unlike variables, constants must be initialized at the time of declaration.
  • Are constants scoped like variables?

    Yes, constants follow the same scoping rules as variables. A constant declared inside a function is only accessible within that function, while a constant declared outside of any function is accessible throughout the package.