YouTip LogoYouTip

Go Break Statement

Go Language break Statement

Go Language Loop Statements Go Language Loop Statements

In Go, the break statement is used to terminate the execution of the current loop or switch statement, and to jump out of the code block of that loop or switch statement.

The break statement can be used in the following aspects:

  • Used in loop statements to exit the loop and start executing statements after the loop.
  • In a switch statement, break has the effect of jumping out after executing one case.
  • break can be applied in select statements.
  • In multiple nested loops, a label can be used to specify which loop to break out of.

Syntax

The syntax format for break is as follows:

break

The flowchart for the break statement is shown below:

break flowchart

Examples

Using break in a for loop:

Example

package main

import "fmt"

func main() {

    for i := 0; i < 10; i++ {
        if i == 5 {
            break // Exit the loop when i equals 5
        }
        fmt.Println(i)
    }
}

Output:

0
1
2
3
4

Exiting the loop when variable a is greater than 15:

Example

package main

import "fmt"

func main() {
    /* Define local variable */
    var a int = 10

    /* for loop */
    for a < 20 {
        fmt.Printf("a value is: %dn", a)
        a++
        if a > 15 {
            /* Use break statement to exit the loop when a is greater than 15 */
            break
        }
    }
}

In the above example, when the value of a is greater than 15, the break statement is executed, and the entire loop is terminated. The execution result is:

a value is: 10
a value is: 11
a value is: 12
a value is: 13
a value is: 14
a value is: 15

The following example has multiple loops and demonstrates the difference between using a label and not using a label:

Example

package main

import "fmt"

func main() {
    // Without label
    fmt.Println("---- break ----")
    for i := 1; i <= 3; i++ {
        fmt.Printf("i: %dn", i)
        for i2 := 11; i2 <= 13; i2++ {
            fmt.Printf("i2: %dn", i2)
            break
        }
    }

    // With label
    fmt.Println("---- break label ----")
re:
    for i := 1; i <= 3; i++ {
        fmt.Printf("i: %dn", i)
        for i2 := 11; i2 <= 13; i2++ {
            fmt.Printf("i2: %dn", i2)
            break re
        }
    }
}

The execution result of the above example is:

---- break ----
i: 1
i2: 11
i: 2
i2: 11
i: 3
i2: 11
---- break label ----
i: 1
i2: 11

Using break in a switch statement:

Example

import "fmt"

func main() {
    day := "Tuesday"

    switch day {
    case "Monday":
        fmt.Println("It's Monday.")
    case "Tuesday":
        fmt.Println("It's Tuesday.")
        break // Exit the switch statement
    case "Wednesday":
        fmt.Println("It's Wednesday.")
    }
}

Output:

It's Tuesday.

Using break in a select statement:

Example

package main

import (
    "fmt"
    "time"
)

func main() {
    ch1 := make(chan int)
    ch2 := make(chan int)

    go func() {
        time.Sleep(2 * time.Second)
        ch1 <- 1
    }()

    go func() {
        time.Sleep(1 * time.Second)
        ch2 <- 2
    }()

    select {
    case <-ch1:
        fmt.Println("Received from ch1.")
    case <-ch2:
        fmt.Println("Received from ch2.")
        break // Exit the select statement
    }
}

Output:

Received from ch2.

In Go, the use of the break statement in a select statement is relatively special. Due to the nature of the select statement, the break statement cannot directly exit the select statement itself, because the select statement is non-blocking and will wait until all communication operations are ready. If you need to terminate the execution of a select statement early, you can use the return or goto statement to achieve the same effect.

The following example demonstrates using return to terminate execution early in a select statement:

Example

package main

import (
    "fmt"
    "time"
)

func process(ch chan int) {
    for {
        select {
        case val := <-ch:
            fmt.Println("Received value:", val)
            // Execute some logic
            if val == 5 {
                return // Terminate the select statement execution early
            }
        default:
            fmt.Println("No value received yet.")
            time.Sleep(500 * time.Millisecond)
        }
    }
}

func main() {
    ch := make(chan int)
    go process(ch)

    time.Sleep(2 * time.Second)
    ch <- 1

    time.Sleep(1 * time.Second)
    ch <- 3

    time.Sleep(1 * time.Second)
    ch <- 5

    time.Sleep(1 * time.Second)
    ch <- 7

    time.Sleep(2 * time.Second)
}

In the above example, the process function uses a select statement in an infinite loop to wait for data on the channel ch. When data is received, some logic is executed. When the received value equals 5, return is used to terminate the execution of the select statement early.

Output:

No value received yet.
No value received yet.
Received value: 1
No value received yet.
Received value: 3
No value received yet.
Received value: 5

By using return, we can terminate execution early within a select statement and return to the caller's code.

It is important to note that using the return statement will immediately terminate the execution of the current function, so please decide based on actual requirements how to terminate execution early in a select statement.

Go Language Loop Statements Go Language Loop Statements

← Go Function Call By ReferenceGo Functions β†’