Go programming Langauge break

Go Programming Langauge break

break is used to stop the current loop or iterations.

Go break Example

Below code explains how break will be used to stop the looping.

package main                                                               	 
                                                                           	 
import "fmt"                                                               	 
                                                                           	 
func main() {                                                              	 
                                                                           	 
	for i:=5;i>0;i-- {                                                     	 
    	if i == 2 {                                                        	 
        	break;                                                         	 
    	}                                                                  	 
    	fmt.Printf("Iteration: %d\n", i)                                   	 
	}                                                                      	 
}
Output:
$ go build for-loop.go
$ ./for-loop
Iteration: 5
Iteration: 4
Iteration: 3

Go Nested for Loop with break

break is used to stop only current loop and not the outer loops.

package main                                                               	 
                                                                           	 
import "fmt"                                                               	 
                                                                           	 
func main() {                                                              	 
                                                                           	 
	for j:=0;j<3;j++ {                                                     	 
    	for i:=5;i>0;i-- {                                                 	 
        	if i == 2 {                                                    	 
            	break;                                                     	 
        	}                                                              	 
        	fmt.Printf("Iteration- outer: %d, inner: %d\n", j,i)           	 
    	}                                                                  	 
	}                                                                      	 
}
Output:
$ go build for-loop.go
$ ./for-loop
Iteration- outer: 0, inner: 5
Iteration- outer: 0, inner: 4
Iteration- outer: 0, inner: 3
Iteration- outer: 1, inner: 5
Iteration- outer: 1, inner: 4
Iteration- outer: 1, inner: 3
Iteration- outer: 2, inner: 5
Iteration- outer: 2, inner: 4
Iteration- outer: 2, inner: 3