Loops allows you to easily repeat code by telling the compiler how many times to execute a block of code. In this article, we will learn how to use loops in Go.
Go is slightly different than other languages. It combines some modern take on for loops and removes older versions. There are three basic ways to do loops in Go. One note, is that if you come from other languages, go does not have a while
loop. You will use the for
keyword.
The first way to compare a loop is the classic for loop and follows the following format. Here we say, i = 0, while i is less than 10, increment i and execute the block of code.
for i := 0, i < 10; i++ {
// code
}
The second loop type is more like a while loop. It has the following structure below. Here we say, while i is less than 10, execute the following code. Notice that we increment i inside our code block. If you don't do this, you will have an infinite loop.
for i < 10 {
i++
}
The third loops type is a more modern take. This allows use to execute a loop over an array which is one of the most common tasks in programming. Here we say, give me the index and element from this array. We use a new range
keyword to extract each index and element, then execute a block of code.
numbers := [4]int{1, 2, 3, 5}
for index, element := range numbers {
// do code
}
Here is the full example code for you to use. Copy the ode to a file main.go
and then you can run this by typing go run main.go
in your command line.
package main
import "fmt"
func main() {
var a int
for a := 0; a < 10; a++ {
fmt.Printf("a: %d \n", a)
}
for a < 10 {
a++
fmt.Printf("a: %d \n", a)
}
numbers := [4]int{1, 2, 3, 4}
for index, element := range numbers {
fmt.Printf("i: %d, x: %d \n", index, element)
}
}