DEV Community

Cover image for golang break for loop
tcs224
tcs224

Posted on

golang break for loop

In Go you can use a for loop to repeat code. The for loop exists in many programming languages. But how do you stop a for loop?

By default, it stops if a condition is true. In Go, this repeats while i is smaller than 5. If its greater it stops.

for i := 0; i < 5; i++ {

This works well, but what if conditions are not right? Like this:

for i := 0; i > -1; i++ {

Then it keeps repeating over and over.

Infinite loop

An infinite loop is a loop the stays in the loop indefinitely. In Golang you can create this type of loop:

for {

So when would this for loop end?

package main

import "fmt"

func main() {
    i := 0
    for {
        fmt.Println("i is:", i)
        i++;
    }
    fmt.Println("Statement after for loop.")
}

It doesn't end by default, this creates an infinite loop in Go. So this outputs..

...
i is: 59641
i is: 59642
i is: 59643
i is: 59644
i is: 59645
...

ad infinitum.

Break keyword

To get out of the loop, you can use the break keyword. The break exits the infinite loop, but it has to do so conditionally.

if i >= 10 { break }

So that would give you the code:

package main

import "fmt"

func main() {
    i := 0
    for {
        if i >= 10 { break }
        fmt.Println("i is:", i)
        i++;
    }
    fmt.Println("Statement after for loop.")
}

Related links:

Latest comments (0)