'Break' as the name suggests, is used to break out of a loop(i.e. 'for loop') before its execution is complete.
To make it a little simpler, let us take the below example.
Say you have a 'for loop' that is used to print the numbers from 1 to 5.
package main import "fmt" func main() { for i := 1; i <= 5; i++ { fmt.Println(i) } }
But let us say, you want to 'break' out of the 'while loop', if the value of 'x' is '3'.
i.e. You want to get out of the loop, right after printing 1, 2 and 3.
And we can achieve it using 'break' statement.
Let us modify the above program using the 'break' statement.
package main import "fmt" func main() { for i := 1; i <= 5; i++ { fmt.Println(i) if (i == 3) { break } } }
And all we have done is placed an 'if' condition, right after the print statement, checking if the value of 'x' is equal to '3'. If so we break out of the loop.
if (i == 3) { break }
And the 'break' statement helps to get out of the 'for loop'.