Go for Loop
When you need to run the same block of code a set number of times, reach for a for loop.
Many languages offer several kinds of loop, but Go has just this one.
Go for Loop Syntax
statement1 sets the starting value of the loop counter.
statement2 is the test made for every iteration. A true result keeps the loop going, and a false result stops it.
statement3 raises the counter.
Example
Output: Go program and captured output
package main
import ("fmt")
func main() {
for i := 0; i < 5; i++ {
fmt.Println(i)
}
}
for Loop Syntax
for statement1; statement2; statement3 {
// code to be executed for each iteration
}
The continue Statement
Use continue when you want to skip the rest of the current iteration and carry on with the next one. One or more iterations can be skipped this way. Here the value 3 is skipped, so it never gets printed.
Example
Output: Go program and captured output
package main
import ("fmt")
func main() {
for i := 0; i < 5; i++ {
if i == 3 {
continue
}
fmt.Println(i)
}
}
The break Statement
A break statement ends the loop right away, even if its condition is still true. Here the loop stops as soon as i reaches 3.
Example
Output: Go program and captured output
package main
import ("fmt")
func main() {
for i := 0; i < 5; i++ {
if i == 3 {
break
}
fmt.Println(i)
}
}
Nested Loops
One loop can sit inside another. For every single pass of the outer loop, the inner loop runs from start to finish. In this example, each adjective is printed with each of the three fruits.
Example
Output: Go program and captured output
package main
import ("fmt")
func main() {
adj := [2]string{"big", "tasty"}
fruits := [3]string{"apple", "orange", "banana"}
for i := 0; i < len(adj); i++ {
for j := 0; j < len(fruits); j++ {
fmt.Println(adj[i], fruits[j])
}
}
}
The range Keyword
To go through the elements of an array, slice or map with less code, use the range keyword. In this example, it gives you the index and the value of each element of the array.
Example
Output: Go program and captured output
package main
import ("fmt")
func main() {
fruits := [3]string{"apple", "orange", "banana"}
for idx, val := range fruits {
fmt.Printf("%v\t%v\n", idx, val)
}
}