0
0
Goprogramming~5 mins

Break statement in Go

Choose your learning style9 modes available
Introduction

The break statement stops a loop or switch early. It helps you exit when you find what you want or need to stop.

When searching a list and you find the item you want, stop checking more.
When reading input until a special value appears, then stop reading.
When looping but a condition outside the loop says to stop immediately.
When you want to exit a switch case early to avoid running other cases.
Syntax
Go
break

The break statement has no extra words or symbols.

It works inside loops (for) and switch statements.

Examples
This loop prints numbers 0 to 4, then stops when i is 5.
Go
for i := 0; i < 10; i++ {
    if i == 5 {
        break
    }
    fmt.Println(i)
}
The break ends the Saturday/Sunday case early, though in Go it is optional because cases do not fall through by default.
Go
switch day := "Monday"; day {
case "Saturday", "Sunday":
    fmt.Println("Weekend")
    break
case "Monday":
    fmt.Println("Start of week")
}
Sample Program

This program prints numbers from 1 to 5. When i reaches 6, the break stops the loop.

Go
package main

import "fmt"

func main() {
    for i := 1; i <= 10; i++ {
        if i == 6 {
            break
        }
        fmt.Println(i)
    }
}
OutputSuccess
Important Notes

In Go, break only stops the innermost loop or switch.

Unlike some languages, Go switch cases do not fall through by default, so break is often not needed there.

Use break carefully to avoid skipping important code unintentionally.

Summary

The break statement stops loops or switch cases early.

It helps control when to exit repeating actions.

In Go, break is simple and only affects the closest loop or switch.