Foreach Loops: The Go Way
·
204 words
·
1 minute read
The foreach keyword itself does not exist within Go, instead the for
loop can be adapted to work in the same manner. The difference however, is by using the range
keyword and a for loop together. Like foreach loops in many other languages you have the choice of using the slices' key or value within the loop.
Example 1)
In our example, we iterate over a string slice and print out each word. As we only need the value we replace the key with an underscore.
|
|
Example 2)
Likewise, if we want to iterate and loop over each entry in a map, as you would an array, you can in the same way.
|
|