Go Programming - Constants
What are Constants?
Constants are immutable values which are known at compile time and do not change for the life of the program. They can be of any of the basic data types, such as int
, float
, string
, and boolean
.
Declaring Constants
In Go, constants are declared using the const
keyword. The syntax is similar to variable declarations except that the const
keyword is used.
const pi = 3.14
This declares a constant named pi
with a value of 3.14
.
Typed and Untyped Constants
Constants in Go can be either typed or untyped. An untyped constant does not have a specific type until it is given one, while a typed constant is explicitly declared with a specific type.
const a = 42
const b int = 42
In the above example, a
is an untyped constant and b
is a typed constant of type int
.
Multiple Constants Declaration
Go allows multiple constants to be declared in a block, which is useful for grouping related constants together.
const ( Pi = 3.14 E = 2.71 G = 9.81 )
This declares three constants Pi
, E
, and G
in a single block.
Enumerated Constants
Go supports enumerated constants, which are a set of related constants. The iota
identifier is used to simplify the creation of enumerated constants.
const ( Sun = iota Mon Tue Wed Thu Fri Sat )
In the above example, Sun
is assigned 0, Mon
is assigned 1, and so on. The iota
identifier is reset to 0 whenever the const
keyword appears in the source code.
Examples of Constants in Go
Here are some practical examples to illustrate the use of constants in Go:
package main
import "fmt"
func main() {
const Pi = 3.14
const Greeting = "Hello, World!"
fmt.Println("Value of Pi:", Pi)
fmt.Println(Greeting)
}
Output:
Value of Pi: 3.14
Hello, World!
Conclusion
Constants are a crucial part of programming in Go. They allow you to define fixed values that remain unchanged throughout the execution of your program. By using constants, you can make your code more readable and maintainable.