Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a foreach loop in Go?

Tags:

foreach

slice

go

Is there a foreach construct in the Go language? Can I iterate over a slice or array using a for?

like image 660
tatsuhirosatou Avatar asked Oct 16 '11 04:10

tatsuhirosatou


People also ask

How do you loop an array in Golang?

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.

Does Go have while loop?

There is no do-while loop in Go.

What are the looping constructs 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.


Video Answer


1 Answers

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.

like image 168
5 revs, 4 users 40% Avatar answered Sep 18 '22 14:09

5 revs, 4 users 40%