This blog describes Loop Control Statements in Go.
Loop control statements in Go allow you to control the flow of loops. Go supports for
, break
, continue
, and goto
statements. Here’s how each of these works:
for
Loop
The for
loop in Go is the only looping construct. It supports three forms.
- The basic
for
loop, similar to other languages.
for initialization; condition; post {
// code to execute
}
For example.
for i := 0; i < 5; i++ {
fmt.Println(i)
}
2. The for
loop as a while
loop
for condition {
// code to execute
}
For example.
sum := 0
for sum < 10 {
sum += 2
}
3. The infinite loop.
for {
// code to execute indefinitely
}
For example.
package main
import "fmt"
func main() {
// Infinite loop using the for loop syntax without any condition
for {
fmt.Println("This is an infinite loop.")
}
}
break
Statement
The break
statement is used to terminate the loop prematurely.
For Example.
for i := 0; i < 10; i++ {
fmt.Println(i)
if i == 5 {
break
}
}
continue
Statement
The continue
statement is used to skip the current iteration of the loop and move to the next iteration.
For Example.
for i := 0; i < 10; i++ {
if i%2 == 0 {
continue
}
fmt.Println(i)
}
goto
Statement
The goto
statement transfers control to a labeled statement. It’s rarely used and often considered harmful because it can make code less readable and harder to understand.
For Example.
i := 0
Loop:
for i < 10 {
fmt.Println(i)
i++
if i == 5 {
goto Loop
}
}
These are the basic loop control statements in Go. They provide flexibility in controlling the execution flow within loops. However, it’s essential to use them judiciously to maintain code readability and avoid unnecessary complexity.
Further Reading
Variables and Data Types in Go
Go Programming Practice Exercise
Program Structure in Go Programming Language
Spring Framework Practice Problems and Their Solutions
How to Create and Run a Simple Program in Go?
20+ Interview Questions on Go Programming Language
From Google to the World: The Story of Go Programming Language
Why Go? Understanding the Advantages of this Emerging Language