Is there a foreach construct in the Go language?

Technology CommunityCategory: GolangIs there a foreach construct in the Go language?
VietMX Staff asked 3 years ago

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.

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
}