Break Statement in Go
In this tutorial, we will learn about the break statement in Go. We will cover the basics of using the break statement to exit loops and switch statements.
What is a Break Statement
A break statement is used to terminate the execution of a loop or switch statement. When a break statement is encountered, control is transferred to the statement immediately following the loop or switch.
Syntax
The syntax for the break statement in Go is:
break
The break statement can be used in for, switch, and select statements to exit the current loop, switch, or select block prematurely.
Example 1: Exiting a For Loop Early
- Use a for loop to iterate from 1 to 10.
- Inside the loop, use an if statement to check if
i
is equal to 5. - If the condition is true, use a break statement to exit the loop.
- Print the value of
i
.
Go Program
package main
import "fmt"
func main() {
for i := 1; i <= 10; i++ {
if i == 5 {
break
}
fmt.Printf("%d ", i)
}
}
Output
1 2 3 4
Example 2: Exiting a Switch Statement
- Assign a value to a variable
num
. - Use a switch statement to check the value of
num
. - Use a case statement for different values of
num
. - Inside each case, use a break statement to exit the switch statement after the matching case block is executed.
- Print a message indicating the value of
num
.
Go Program
package main
import "fmt"
func main() {
num := 2
switch num {
case 1:
fmt.Println("Number is 1")
case 2:
fmt.Println("Number is 2")
case 3:
fmt.Println("Number is 3")
default:
fmt.Println("Number is not 1, 2, or 3")
}
}
Output
Number is 2