Go break Statement

Introduction

The break statement in Go is used to exit a loop or switch statement prematurely. It allows you to terminate the execution of a loop or switch case before it completes all its iterations or checks all its cases. In this chapter, you will learn the syntax and usage of the break statement in Go, with examples to illustrate how it works.

Syntax

The break statement can be used within loops (for) and switch statements to exit the loop or switch case immediately.

Syntax:

break

Examples

break in a For Loop

The break statement can be used to exit a for loop when a certain condition is met.

Example:

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
    }
    fmt.Println("Loop exited")
}

break in a Nested Loop

The break statement only exits the nearest enclosing loop. To exit an outer loop from within a nested loop, you can use labels.

Example:

package main

import "fmt"

func main() {
    outer:
    for i := 0; i < 3; i++ {
        for j := 0; j < 3; j++ {
            if i == 1 && j == 1 {
                break outer
            }
            fmt.Printf("i: %d, j: %d\n", i, j)
        }
    }
    fmt.Println("Exited the outer loop")
}

break in a Switch Statement

The break statement is implicit in Go’s switch statement, meaning that it automatically exits the switch case after executing the matched case. However, you can use break explicitly to improve code readability or to break out of a nested loop within a switch case.

Example:

package main

import "fmt"

func main() {
    day := 3

    switch day {
    case 1:
        fmt.Println("Monday")
    case 2:
        fmt.Println("Tuesday")
    case 3:
        fmt.Println("Wednesday")
        break // Explicit break, though not necessary here
    case 4:
        fmt.Println("Thursday")
    case 5:
        fmt.Println("Friday")
    default:
        fmt.Println("Weekend")
    }
}

Conclusion

The break statement in Go is a powerful control structure that allows you to exit loops and switch cases prematurely. It is useful for terminating loops when certain conditions are met and for improving code readability in switch statements. By understanding how to use the break statement, you can better control the flow of your programs and handle various scenarios more effectively.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top