search

What is the difference between Go's for-range loop and for-condition loop?

In Go, the for-range loop and the for-condition loop have different syntax and are used for different purposes.

The **for-range** loop is used for iterating over arrays, slices, maps, and strings. It has the following syntax:

for key, value := range collection {
    // loop body
}

The loop variable **key** is optional and is used to store the key of the current element in a map or the index of the current element in an array or slice. The loop variable **value** is mandatory and is used to store the value of the current element. The **collection** can be an array, slice, map, or string.

The **for-condition** loop, on the other hand, is used for executing a block of code repeatedly while a condition is true. It has the following syntax:

for initialization; condition; post {
    // loop body
}

The **initialization** statement is optional and is used to initialize a loop variable. The **condition** expression is mandatory and is evaluated before each iteration of the loop. If the condition is true, the loop body is executed. The **post** statement is optional and is executed at the end of each iteration of the loop.

In summary, the **for-range** loop is used for iterating over collections, while the **for-condition** loop is used for executing a block of code repeatedly while a condition is true.

Related Questions You Might Be Interested