Golang Iteration/loop: Break & continue



package main

import "fmt"

var pows = []int{1, 2, 4, 8, 16, 32, 64, 128}
var users = []string{"yuna", "yuni", "yuka", "deisy", "Miyem", "Jhony", "Merry", "Toni"}

func main() {
	for x, value := range pows {

		fmt.Println(x, ":", value)

		if value >= 16 {
			// After x is greater or equal to 16 stop the iterate
			break
		}
	}

	for x, value := range pows {

		fmt.Println(x, ":", value)

		if value >= 16 {
			continue
		}

		// After x is greater or equal to 16 do  not print this
		fmt.Println("------")
	}

}

Golang Output

0 : 1

1 : 2

2 : 4

3 : 8

4 : 16

 

0 : 1

——

1 : 2

——

2 : 4

——

3 : 8

——

4 : 16

5 : 32

6 : 64

7 : 128

Success: process exited with code 0.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s