Beginner Fundamentals

For Loops

Go has only one looping keyword: for. It is flexible enough to cover every kind of loop.

Classic for

The full form has an init, a condition and a post statement.

for i := 0; i < 5; i++ {
    fmt.Println(i)
}

While-like for

Drop the init and post to get a while loop.

n := 1
for n < 100 {
    n *= 2
}
fmt.Println(n) // 128

Infinite loop

With no condition it runs forever until you break.

count := 0
for {
    count++
    if count == 3 {
        break
    }
}
fmt.Println(count) // 3

range

range iterates over collections, giving an index and a value.

fruits := []string{"apple", "pear", "plum"}
for i, fruit := range fruits {
    fmt.Println(i, fruit)
}

Use the blank identifier _ to ignore a value you do not need.

for _, fruit := range fruits {
    fmt.Println(fruit)
}