In Go programming language, constants are like variables but their values cannot be changed once they are declared. They are immutable, meaning their values stay the same throughout the execution of the program. Constants are a fundamental concept in programming, providing a way to define fixed values that are used throughout the code. In this chapter, we will explore constants in Go, starting from the basics and gradually moving towards more advanced concepts.
Constants in Go are declared using the const
keyword followed by the constant name and its value. Unlike variables, constants must be assigned a value at the time of declaration, and this value cannot be modified later.
const pi = 3.14159
const appName string = "MyGoApp"
Constants can be of various types such as integer, floating-point, string, Boolean, etc. The type can be explicitly specified or inferred by the compiler.
const (
daysInWeek = 7
hoursInDay int = 24
)
Constants in Go can be typed or untyped. Untyped constants do not have a fixed type and can be implicitly converted by the compiler when used in expressions. Typed constants, on the other hand, have a specific type associated with them.
const (
radius = 5.0 // untyped constant
days int = 30 // typed constant
)
var area float64 = pi * (radius * radius)
In the above example, radius
is an untyped constant, so it can be directly used in expressions without explicit conversion. However, days
is a typed constant, so it has a fixed type (int
) and can only be used in expressions where an int
is expected.
Enumerated constants are a set of related constants that represent a sequence of values. They are often used to define a list of named constants that have a logical order.
const (
Monday = iota // 0
Tuesday // 1
Wednesday // 2
Thursday // 3
Friday // 4
Saturday // 5
Sunday // 6
)
In the above example, iota
is a predeclared identifier in Go that represents successive integer constants. It starts with 0
and increments by 1
for each subsequent constant declaration within the same const
block.
Constants in Go can also be used in more advanced scenarios such as within expressions, function arguments, and even as the size of array types.
const (
kb = 1024
mb = 1024 * kb
gb = 1024 * mb
)
func printBytes(numBytes int) {
fmt.Println("Bytes:", numBytes)
}
func main() {
printBytes(gb)
}
In the above example, kb
, mb
, and gb
are constants representing kilobytes, megabytes, and gigabytes respectively. These constants are then used in the printBytes
function to print the size in bytes.
Constants are an essential part of programming in Go, providing a way to define fixed values that remain constant throughout the execution of a program. They help in making code more readable, maintainable, and less error-prone by eliminating magic numbers and strings scattered throughout the code. By understanding the basics and advanced concepts of constants in Go, developers can write more robust and efficient programs. Happy coding !❤️