patterngoCritical
Is there a foreach loop in Go?
Viewed 0 times
loopforeachthere
Problem
Is there a
Can I iterate over a slice or array using a
foreach construct in the Go language?Can I iterate over a slice or array using a
for?Solution
From For statements with range clause:
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:
If you don't care about the index, you can use
The underscore,
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.Context
Stack Overflow Q#7782411, score: 1161
Revisions (0)
No revisions yet.