Repeat! Repeat!

In Go, there is only one kind of loop: for. But that single for can handle every kind of repetition.


Say hello 10 times

for i := 0; i < 10; i++ {
    fmt.Println("Hello, Go!")
}

Translation:

(Start at 0, while less than 10, increase by 1) repeat {
    print "Hello, Go!" and move to the next line
}

Take items out of a bundle one by one (range)

Most commonly used to pull items from a slice.

foods := []string{"chicken", "pizza", "tteokbokki"}

for index, food := range foods {
    fmt.Println(index, "menu:", food)
}

Translation:

Repeat while taking index and food from the foods bundle {
    print the number and the menu name, then move to the next line
}

Repeat until the condition fails (like while)

Go does not have a while, but if you put only a condition after for, it works the same.

energy := 3

for energy > 0 {
    fmt.Println("Energy left:", energy)
    energy-- // decrease by one
}

Translation:

While energy is greater than 0, repeat {
    print "Energy left" and energy, then move to the next line
    subtract 1 from energy
}

Simple and powerful. That is Go’s looping style.