Golang for Loop Examples: Foreach and While

Use the for-loop to iterate through numbers. Look at foreach and while loops.

For-loop. Go has 1 loop: the for-loop. But this loop can be used in many ways, to loop from a start to an end, or until a condition is reached.

With range, a keyword, we can iterate over more complex things like slices or maps. Range, used with for, helps us manage iteration.

An example. This code uses the classic for-loop where we begin at a certain number and end at another. After each body evaluation, the index is incremented (1 is added to it).
Syntax: The variable i is declared and initialized to 0. The ":=" syntax indicates that this is a new variable.
Semicolons: We separate the 3 clauses of this form of the for-loop with semicolons. Braces are used for the loop body.
Golang program that uses for-loop from start to end package main import "fmt" func main() { // Loop from 0 until 5 is reached. for i := 0; i < 5; i++ { // Display integer. fmt.Println(i) } } Output 0 1 2 3 4

Condition, while. There is no while keyword here, but the for-loop can be used as a while-loop. It continues while the condition specified after "for" is true.
Here: The variables "valid" and "i" are initialized. While "valid" is true, the loop continues iterating.
End: The loop terminates after the variable "i" is incremented to 3, and valid is set to false.
Golang program that uses for condition, while loop package main import "fmt" func main() { valid := true i := 0 // This loop continues while "valid" is true. for valid { // If i equals 3, set "valid" to false. if i == 3 { valid = false } fmt.Println(i) i++ } } Output 0 1 2 3

No condition, break. A for-loop can be specified with no condition. This loop continues infinitely until broken (as by a return or break statement).
Tip: This is the same as a "while true" loop in other languages. It is a loop that has no specified terminating condition.
Golang program that uses for, no condition package main import "fmt" func main() { id := 10 // This loop continues infinitely until broken. for { // Break if id is past a certain number. if id > 20 { break } fmt.Println(id) id += 5 } } Output 10 15 20

Range and slice. The range keyword is used with a for-loop. When we use range on a slice, all the indexes in the slice are enumerated.range
So: The range of the three-element int slice here returns 0, 1 and 2. We use those to get elements from the slice.
Golang program that uses for and range, slice package main import "fmt" func main() { // Create a slice of three ints. ids := []int{10, 21, 35} // Loop over range of indexes in the slice. for i := range ids { fmt.Println(ids[i]) } } Output 10 21 35

Foreach loop. Golang does not have a foreach keyword. But we can use a foreach loop by receiving 2 values in a for-range loop. We ignore the first, and the second is each element's value.
Golang program that uses foreach loop package main import "fmt" func main() { // Two strings in a slice. animals := []string{"bird", "frog"} // Loop over each element directly (foreach loop). // ... Ignore the first pair of each returned pair (the index). for _, animal := range animals { fmt.Println(animal) } } Output bird frog

Decrement. A loop can decrement from a higher number to a lower one. We often test for >= 0 in this case. The decrement statement uses two minus signs.
Golang program that uses for, decrements index package main import "fmt" func main() { // Decrement loop. for i := 4; i >= 0; i-- { // Display loop index. fmt.Println(i) } } Output 4 3 2 1 0

Continue. This keyword ends the current iteration of a loop, but then the next iteration begins as usual. Unlike break, the loop itself is not terminated.
Here: When an element in the int slice equals 10, we use continue to stop processing of the current iteration.
Golang program that uses continue package main import "fmt" func main() { elements := []int{10, 20} for i := range elements { // If element is 10, continue to next iteration. if elements[i] == 10 { fmt.Println("CONTINUE") continue } fmt.Println("ELEMENT:", elements[i]) } } Output CONTINUE ELEMENT: 20

A summary. The for-loop in Go has many purposes. We use one of its forms to iterate in many ways. With range, a helpful keyword, we iterate in a clear way over collections.Built-Ins

© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.