Is there a foreach
construct in the Go language? Can I iterate over a slice or array using a for
?
Explanation: The variable i is initialized as 0 and is defined to increase at every iteration until it reaches the value of the length of the array. Then the print command is given to print the elements at each index of the array one by one.
There is no do-while loop in Go.
Go has only one looping construct, the for loop. The basic for loop has three components separated by semicolons: the init statement: executed before the first iteration. the condition expression: evaluated before every iteration.
https://golang.org/ref/spec#For_range
A "for" statement with a "range" clause iterates through all entries of an array, slice, string or map, or values received on a channel. For each entry it assigns iteration values to corresponding iteration variables and then executes the block.
As an example:
for index, element := range someSlice { // index is the index where we are // element is the element from someSlice for where we are }
If you don't care about the index, you can use _
:
for _, element := range someSlice { // element is the element from someSlice for where we are }
The underscore, _
, is the blank identifier, an anonymous placeholder.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With