Golang : For loop continue,break and range
Feeling like writing about FOR loop today so....this tutorial will explore how Golang's FOR loop works.
For loop is a block of code that repeats itself with increase/decrease or changes in input variables until certain condition is met. In the simplest form a for loop looks like this :
package main
import "fmt"
func main() {
// initialize i to 0
// check each time if i is less than 10
// the increase the value of i by 1 for each loop after the first
for i := 0; i < 10; i++ {
fmt.Printf("i is %d\n", i)
}
}
Output :
i is 0
i is 1
i is 2
i is 3
i is 4
i is 5
i is 6
i is 7
i is 8
i is 9
Another example but with string value instead of integer
package main
import "fmt"
func main() {
s := "" // initialize s to empty string
for s != "eeeee" { // if s is not 5 e
fmt.Printf("s is %s\n", s)
s = s + "e" // add e to s (string value!) and repeat
}
}
Output :
s is
s is e
s is ee
s is eee
s is eeee
Just in case you have multiple counters to take into account for your FOR loop. No problem. See this example
package main
import "fmt"
func main() {
// multiple counters initialization
// combine each conditions with &&(and) and ||(or) to form the final boolean condition
// incrementation of the multiple counters
for i, j, s := 0, 5, "e"; i < 10 && j < 100 && s != "eeeee"; i, j, s = i+1, j+1, s+"e" {
fmt.Println("Value of i, j, s:", i, j, s)
}
}
break keyword :
Basically break will stop the for loop entirely once a condition is met.
To break the for loop, see this code fragment. (taken from Read until certain condition is met tutorial )
var userInput []string
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
line := scanner.Text()
if line == "." {
break // to stop writing enter . (period) and press enter
}
userInput = append(userInput, line+"\n")
}
continue keyword
continue is the opposite of break keyword, basically what it allows you to do is to skip when a condition is met and continue with the for loop again.
this code example demonstrate how the continue keyword works in a for loop
package main
import "fmt"
func main() {
for i := 0; i < 9; i++ {
if i%2 == 0 {
continue //skip this part and go back to beginning of for loop
}
fmt.Println("The odd number you are looking for :", i)
}
}
range keyword :
range allows you to iterate each key/value in an array, slice or map. If used against a map, range will return 2 values - the index(key) and the related values. See example below :
package main
import (
"fmt"
)
func main() {
niceplacestovisit := []string{"Paris", "Kyoto", "Bali", "New York"}
i := 1
for cityname := range niceplacestovisit {
fmt.Printf("[%d] city name is %s\n", i, niceplacestovisit[cityname])
i++
}
fmt.Println("------------------------")
// range also return 2 values
// 1st the index or key
// 2nd the value
niceplacestovisit2 := map[string]string{"1":"Paris", "2":"Kyoto", "3":"Bali", "4":"New York"}
for cityname2, value := range niceplacestovisit2 {
fmt.Printf("[%s] city name is %s\n", cityname2, value)
}
// starting from Go 1.4
// it is ok to iterate without specifying the values
for range niceplacestovisit2 {
fmt.Println("Many cities iterated over niceplacestovisit2 array")
}
}
Output :
1 city name is Paris
[2] city name is Kyoto
[3] city name is Bali
[4] city name is New York
1 city name is Paris
[2] city name is Kyoto
[3] city name is Bali
[4] city name is New York
Many cities iterated over niceplacestovisit2 array
Many cities iterated over niceplacestovisit2 array
Many cities iterated over niceplacestovisit2 array
Many cities iterated over niceplacestovisit2 array
Hope this tutorial be useful to you in learning Golang.
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+33.6k Golang : Create x509 certificate, private and public keys
+17.2k Golang : Clone with pointer and modify value
+13.9k Golang : How to convert a number to words
+21.7k Golang : Convert seconds to minutes and remainder seconds
+5.8k Golang : Experimenting with the Rejang script
+13.7k Golang : Reverse IP address for reverse DNS lookup example
+7.3k SSL : How to check if current certificate is sha1 or sha2 from command line
+42.8k Golang : Get hardware information such as disk, memory and CPU usage
+22.1k Golang : How to read JPG(JPEG), GIF and PNG files ?
+12.3k Golang : Transform comma separated string to slice example
+17.3k How to enable MariaDB/MySQL logs ?
+5.2k How to check with curl if my website or the asset is gzipped ?