Premium Tutorials • Books • Articles • Modern Programming Paths Go Programming Book · Author Bookstore
Lesson 7 of 15

Loops in Go

Repeat tasks using Go's flexible for loop.

Beginner Friendly Runnable Example Go Programming
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

  1. Print numbers from 1 to 10.
  2. Print even numbers from 2 to 20.
  3. Loop through a list of five names.

Continue Learning

After this lesson, continue to the next lesson or explore related tutorials on VisualStudioTutor.com.