Thuta Learning
IntermediateProgrammingbeginner

Loops (For)

Relax. We'll talk through this in plain words — no textbook voice.

In Go, there's only one loop keyword: for. But you can use it in several styles — classic for loop, while-style loop, and range loop.

go
package main

import "fmt"

func main() {
    for i := 1; i <= 3; i++ {
        fmt.Println("count:", i)
    }

    names := []string{"Aung", "Su", "Mya"}
    for _, name := range names {
        fmt.Println("hello", name)
    }
}

The first loop counts from 1 up to 3. The second loop takes each name from the slice and prints a greeting message.

You should see
count: 1 count: 2 count: 3 hello Aung hello Su hello Mya

Info

range gives you the index/key as the first value and the actual item as the second value.

Easy traps

  • If a loop condition is wrong, you can end up with an infinite loop. In server code, an infinite loop can spike the CPU and crash the app.