Looping
Notes// archive From the original Code Walker docs. Kept for reference, so some versions and commands may be out of date.
All loops in Go are variations with the for loops.
Infinite loops#
Example:
main.gogo
package main
import "fmt"
func main() {
counter := 99
for {
fmt.Println(counter)
counter += 1
}
}You can use the break statement to ext a loop:
main.gogo
package main
import "fmt"
func main() {
counter := 99
for {
fmt.Println(counter)
counter += 1
break
}
}Loop until condition#
Example:
package main
import "fmt"
func main() {
counter := 1
for counter < 10 {
fmt.Println(counter)
counter++
}
fmt.Println("Loop completed")
}Counter loop#
Example:
main.gogo
package main
import "fmt"
func main() {
for counter := 0; counter < 10; counter++ {
fmt.Println(counter)
}
fmt.Println("Loop completed")
}Loop over collections#
We can use an array, slice or map for looping over.
Array example:
main.gogo
package main
import "fmt"
func main() {
years := [5]int{1999, 2004, 2010, 2014, 2024}
for index, value := range years {
fmt.Println(index, value)
}
fmt.Println("Loop completed")
}Map example:
main.gogo
package main
import "fmt"
func main() {
type petRecords struct {
id int
animal map[string]string
age int
}
pets := []petRecords{
{id: 1, animal: map[string]string{"name": "Mollie", "Breed": "jack russell"}, age: 10},
{id: 2, animal: map[string]string{"name": "Murphy", "Breed": "terrier"}, age: 8},
}
for _, pet := range pets {
fmt.Println("ID:", pet.id)
for key, value := range pet.animal {
fmt.Println(key, ":", value)
}
fmt.Println("Age:", pet.age)
fmt.Println("--------------")
}
fmt.Println("Loop completed")
}