I saw this question that for correct answer had 'for and range'.
But the for statement is the only available looping statement in Go,and the range keyword allows you to iterate over items of a list like an array or a map. For understanding it, you could translate the range keyword to for each index of.
//for loop
package main
import "fmt"
func main() {
for i := 0; i < 5; i++ {
fmt.Println("Value of i is now:", i)
}
}
//range is used inside a for loop
a := [...]string{"a", "b", "c", "d"}
for i := range a {
fmt.Println("Array item", i, "is", a[i])
}
capitals := map[string] string {"France":"Paris", "Italy":"Rome", "Japan":"Tokyo" }
for key := range capitals {
fmt.Println("Map item: Capital of", key, "is", capitals[key])
}
//range can also return two items, the index/key and the corresponding value
for key2, val := range capitals {
fmt.Println("Map item: Capital of", key2, "is", val)
}
I think the question is about Different Forms of For Loop:
simple loop variants working sample:
package main
import "fmt"
func main() {
//0 1 2 3 4 5 6 7 8 9
for i := 0; i < 10; i++ {
fmt.Print(i, " ")
}
fmt.Println()
i := 0
for ; i < 10; i++ {
fmt.Print(i, " ")
}
fmt.Println()
for i := 0; i < 10; {
fmt.Print(i, " ")
i++
}
fmt.Println()
//2 4 6 8 10 12 14 16 18 20
for i := 1; ; i++ {
if i&1 == 1 {
continue
}
if i == 22 {
break
}
fmt.Print(i, " ")
}
fmt.Println()
i = 0
for {
fmt.Print(i, " ")
i++
if i == 10 {
break
}
}
fmt.Println()
for i, j := 0, 0; i < 5 && j < 10; i, j = i+1, j+2 {
fmt.Println(i, j)
}
}
for array, slice,string, map, channel using range keyword:
package main
import "fmt"
func main() {
ary := [5]int{0, 1, 2, 3, 4}
for index, value := range ary {
fmt.Print("ary[", index, "] =", value, " ")
}
fmt.Println()
for index := range ary {
fmt.Print("ary[", index, "] =", ary[index], " ")
}
fmt.Println()
for _, value := range ary {
fmt.Print(value, " ")
}
fmt.Println()
slice := []int{20, 21, 22, 23, 24, 25, 26, 27, 28, 29}
for index, value := range slice {
fmt.Println("slice[", index, "] =", value)
}
fmt.Println()
str := "Hello"
for index, value := range str {
fmt.Println("str[", index, "] =", value)
}
fmt.Println()
mp := map[string]int{"One": 1, "Two": 2, "Three": 3}
for key, value := range mp {
fmt.Println("map[", key, "] =", value)
}
fmt.Println()
ch := make(chan int, 10)
for i := 0; i < 10; i++ {
ch <- i
}
close(ch)
for i := range ch {
fmt.Print(i, " ")
}
fmt.Println()
}
and Label for break Label and continue Label:
package main
import "fmt"
func main() {
a, b := 1, 1
Loop1:
for {
b++
Loop2:
for {
a++
switch {
case a == 2:
fallthrough
case a == 3:
fmt.Println(3)
case a == 4, a == 5:
continue
case a == 7:
continue Loop1
case a == 9:
break Loop2
case a == 10:
break Loop1
case a == 8:
break
default:
fmt.Println(a, b)
}
}
}
}