Loops in Go
Repeat tasks using Go's flexible for loop.
Learning objective: Use for loops and range loops to repeat tasks.
The for Loop
Go uses for as its main looping statement. It can behave like a traditional for loop or a while-style loop.
Looping with Conditions
A for loop can continue while a condition remains true. This is useful when the number of repetitions is not fixed.
Using range
The range keyword is useful for looping through arrays, slices, maps, and strings.
Example Code
Create or update your Go file, then run the program using go run main.go.
package main
import "fmt"
func main() {
for i := 1; i <= 5; i++ {
fmt.Println("Number:", i)
}
names := []string{"Ali", "Mei", "John"}
for index, name := range names {
fmt.Println(index, name)
}
}
Key points to remember
- Go has no separate while keyword.
- Use break to leave a loop early.
- Use continue to skip to the next loop iteration.
Practice Exercises
- Print numbers from 1 to 10.
- Print even numbers from 2 to 20.
- Loop through a list of five names.
Continue Learning
After this lesson, continue to the next lesson or explore related tutorials on VisualStudioTutor.com.