This golang tutorial help to understand loop statement under the hood of Golang. The loop is used to execute a block of code repeatedly.Go has only one looping construct, the for loop.The Golang doesn’t have while or do-while loops which are present in other programming languages.
The Go for loop has three components separated by semicolons which are following.
- The init statement: The init statement executed before the first iteration. This step allows us to declare and initialize any for loop control variables.
- The condition expression: This statement is evaluated before every iteration occur. If a condition is true, the body of the loop is executed. If the condition is false, then the body of the loop does not execute, and the control flow jumps to a next statement.
- The post statement:This statement executed at the end of every iteration.
The syntax :
for [condition | ( init; condition; increment ) | Range] {
body
}
The simple example using go for loop –
/* main.go */
package main
func main() {
names := []string{"Adam", "Sam", "Daniel"}
for i := 0; i < len(names); i++ {
println(i, names[i])
}
}
As You can see that, There is no parentheses are required to surround for loop statement, but the braces { } are required to execute code block.
Run the golang code –
$go run main.go
Output :
0 Adam<br> 1 Sam<br> 2 Daniel
We can also use the range function with for loop. Let’s see the following example.
/* main.go */
package main
func main() {
names := []string{"Adam", "Sam", "Daniel"}
for i, name := range names {
println(i, name)
}
}
The range is used to iterate on each element of the slice in Go.
Run the golang code –
$go run main.go
Output :
0 Adam 1 Sam 2 Daniel
