In this tutorial, we will learn about constants in Go. We will cover the basics of defining and using constants, including examples of different constant types and their applications.
A constant in Go is a value that cannot be changed once it has been assigned. Constants are defined using the const
keyword and can be of any basic data type.
Constants can be defined in Go using the const
keyword followed by the name of the constant and its value:
const pi = 3.14
Constants can also be defined with explicit type:
const greeting string = "Hello, World!"
We can define a basic constant in Go without specifying its type.
For example,
package main
import "fmt"
func main() {
const pi = 3.14
fmt.Println(pi)
}
3.14
We can define a constant with an explicit type in Go.
For example,
package main
import "fmt"
func main() {
const greeting string = "Hello, World!"
fmt.Println(greeting)
}
Hello, World!
We can use a constant in an if-else statement to check if a number is positive, negative, or zero.
For example,
if
statement to check if the constant is positive, negative, or zero.package main
import "fmt"
func main() {
const number = -10
if number > 0 {
fmt.Println("The number is positive.")
} else if number < 0 {
fmt.Println("The number is negative.")
} else {
fmt.Println("The number is zero.")
}
}
The number is negative.
We can check if a string constant contains a specific substring in Go.
For example,
if
statement to check if the string contains a specific substring.package main
import (
"fmt"
"strings"
)
func main() {
const phrase = "Go is awesome"
if strings.Contains(phrase, "awesome") {
fmt.Println("The phrase contains 'awesome'.")
} else {
fmt.Println("The phrase does not contain 'awesome'.")
}
}
The phrase contains 'awesome'.
We can use a constant to define the number of iterations in a loop.
For example,
for
loop to iterate a constant number of times.package main
import "fmt"
func main() {
const iterations = 5
for i := 1; i <= iterations; i++ {
fmt.Println("Iteration", i)
}
}
Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5