This article will guide you through the basics of loops in Go and show you how to use them effectively.
What are Loops?
Loops are an essential aspect of programming that enables the execution of a particular set of codes multiple times until it accomplishes a specific action.
Loops in Golang
The for loop is the only loop used in Golang, and it executes n number of times depending on the condition specified on the loop statement.
Basic for Loop in Golang
In Go, the basic for loop is frequently used with three parts: initialization statement, condition, and increment statement. The initialization statement initializes the counter variable, while the condition statement determines when the loop should stop. After each iteration, the update statement changes the value of the counter variable. The code within the loop will run endlessly while the condition is true.
For example:
import "fmt"
func main() {
for i := 0; i < 5; i++ {
fmt.Println(i)
}
}
The for keyword is used in this code to begin a loop that will run five times. Initialization statement i:= 0 initializes a variable i to 0 at the beginning of the loop. The loop will keep going while the i <Â 5 condition is true. The i++ command raises i’s value by 1 at the end of each iteration.
The for loop can be used in a variety of ways in Go, and they are as follows:
- Infinite Loop
- While Loop
- Range Based Loop
1: Infinite Loop – Golang
The for loop may also be used as an endless loop by removing every one of the expressions from it. If the user fails to incorporate a condition statement in the for loop, the result of the condition statement is true and the loop goes into an infinite loop.
For example:
import "fmt"
func main() {
for {
fmt.Println("LinuxHint!")
}
}
In the above code, the for keyword is used to begin an infinite loop that will run indefinitely. The loop will keep running forever because no condition is given. We output a message to the console using the fmt.Println method inside the loop. The loop in this example will keep printing “LinuxHint!” to the console until the program is stopped.
2: While Loop – Golang
While loops can be implemented using for loops. The for-loop’s condition expression is changed to match the condition supplied in the while loop. If the condition expression evaluates to true, the loop will keep running; if it evaluates to false, it will stop.
For example:
import "fmt"
func main() {
i := 0
for i < 5 {
fmt.Println("LinuxHint!")
i++
}
}
The for keyword is used in this code to construct a loop that will keep running as long as the condition i<5 is true. ‘Linuxhint!’ is printed to the console using the fmt.Println function inside the loop. The i++ command is then used to increase the value of i.
3: Range-Based Loop – Golang
This kind of for loop is used to repeatedly cycle through the items in a collection (such as an array, slice, or map). The collection to iterate through is specified using the range keyword, and the index and value of each element in the collection are represented by two variables.
For example:
import "fmt"
func main() {
numbers := []int{1, 2, 3, 4, 5}
for _,number := range numbers {
fmt.Println(number)
}
}
In the above code, the values 1, 2, 3, 4, and 5 are created as a slice of integers called numbers. Next, we construct a loop that iterates through each component of the numbers slice using the for keyword. The loop variable _ is used to ignore the index of the current element while the range keyword is used to indicate that we want to iterate over the entire slice. The loop variable number is set to the value of the slice’s presently picked element.
Output
How to Use Golang for Loops with Data Structures
We can use for-loop to go through:
- strings
- arrays
- maps
- structs
1: Strings
Strings in Go are different from those in Python or JavaScript. Each element in a string corresponds to a byte, and they are represented as a UTF-8 sequence of bytes.
Using a standard for-loop or for…range loop, you can iterate across strings.
Loop through a string using the range for-loop:
import "fmt"
func main() {
name := "Linuxhint"
for index, i := range name {
fmt.Println(index, string(i))
}
}
In the above code, we defined a string with various characters. Golang uses strings as bytes, therefore, to print out each value, we have to change its type to string. And then for…range loop is used to loop through each character iteratively and prints it on the screen.
Loop through a string using the regular for-loop:
import "fmt"
func main() {
name := "Linuxhint"
for i := 0; i < len(name); i++ {
fmt.Println(string(name[i]))
}
}
In the above code, the string is looped through iteratively using a regular for-loop and printed on the screen.
2: Arrays
Initializing a variable i to 0 and increasing it until it reaches the array length will allow you to loop over an array with a for-loop.
The syntax is demonstrated below:
// perform an operation
}
Consider the example given below:
import "fmt"
func main() {
num := []int{6, 5, 4, 3, 2, 1}
for i := 0; i < len(num); i++ {
fmt.Println(num[i])
}
}
We looped through an array of integers called numbers by first initializing a variable i. Then, we printed the value of each index in the array while increasing the value of i.
3: Maps
In Go, components are arranged into key-value pairs called maps, where keys are used to differentiate each value. With the for…range loop, which retrieves the index and its related value, we can traverse through a map in Golang.
import "fmt"
func main() {
subjects := map[string]int{
"english": 2,
"computers": 7,
"psychology": 5,
"pharmacy": 9,
}
for key, val := range subjects {
fmt.Println(key, val)
}
}
In the code above, we defined a map that stores information on a bookshop and has an int value and a string key. We then looped over its keys and values using the for…range keyword.
Note: As there is no set order for iterating over a map in Go, we shouldn’t anticipate getting the keys back in the order we stated when we looped through.
4: Structs
A struct in Go can only be cycled through using the reflect package, unlike a map, where we can easily loop over the keys and values. This gives us the ability to change an object of any type.
Let’s construct a struct and iterate through it as an illustration:
import "fmt"
import "reflect"
type Book struct {
Title string
Author string
Price int
Pages int
}
func main() {
b := Book{
Title: "The Godfather",
Author: "Mario Puzo",
Price: 1700,
Pages: 446,
}
values := reflect.ValueOf(b)
types := values.Type()
for i := 0; i < values.NumField(); i++ {
fmt.Println(types.Field(i).Name, values.Field(i))
}
}
In the above code, we defined a Book struct with various attributes and produced a new instance of the struct. The values of the struct and its type were then obtained by using the reflect package. The initialized variable i was incremented by the for-loop until it reached the length of the struct. The field name for each key in the struct is returned by the types.Field(i).Name method. The value for each key in the struct is returned by values.Field(i).
Conclusion
Loops are powerful constructs in Go that enable repetitive actions to execute efficiently without writing redundant codes. The for loop is the only loop used in Go. Loops are used extensively in programming tasks to traverse different data structures, establish control flow, process conditional statements, solve complex problems, and implement algorithms.