Loop Control Statements in Go Language


Loop control statements are used in programming languages to control the flow of loops. These statements help developers to execute certain conditions during loop execution. Go, also known as Golang, is a popular open-source programming language that provides three loop control statements: break, continue, and goto. In this article, we will explore each of these statements in detail and their usage in Go.

The Break Statement

The break statement is used to terminate a loop prematurely. It is usually used when a specific condition is met, and there is no need to continue iterating. The following example shows the usage of the break statement in Go −

Example

In this example, the loop will terminate when i equals 5.

package main

import "fmt"

func main() {
   for i := 0; i < 10; i++ {
      if i == 5 {
         break
      }
      fmt.Println(i)
   }
}

Output

0
1
2
3
4

The Continue Statement

The continue statement is used to skip the current iteration of the loop and move on to the next one. It is typically used when a certain condition is met, and there is no need to execute the current iteration. The following example shows the usage of the continue statement in Go −

Example

In this example, the loop will skip the iteration where i equals 5 and move on to the next one.

package main

import "fmt"

func main() {
   for i := 0; i < 10; i++ {
      if i == 5 {
         continue
      }
      fmt.Println(i)
   }
}

Output

0
1
2
3
4
6
7
8
9

The Goto Statement

The goto statement is used to transfer control to a labeled statement within the same function. It is usually used when a specific condition is met, and the program needs to jump to another part of the code. The following example shows the usage of the goto statement in Go −

Example

package main

import "fmt"

func main() {
   i := 0
   Loop:
      fmt.Println(i)
      i++
      if i < 10 {
         goto Loop
      }
}

Output

0
1
2
3
4
5
6
7
8
9

Conclusion

In conclusion, Go provides three loop control statements: break, continue, and goto. These statements help developers to control the flow of loops and execute certain conditions during loop execution. The break statement is used to terminate a loop prematurely, while the continue statement skips the current iteration of the loop. The goto statement is used to transfer control to a labeled statement within the same function. By using these loop control statements effectively, developers can write efficient and optimized code in Go.

Updated on: 25-Apr-2023

147 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements