Say, you have a String 'x' that has value 'Hello' in it.
Now, you need to iterate all the values of the String.
For range Loop helps to achieve the above scenario.
package main import ("fmt") func main() { x := "Hello" for i,letter := range x { fmt.Printf("Index : %d Value : %c \n", i, letter) } }
So, if you look at the above code, 'for range loop' has a different syntax compared to a 'for loop'.
for i,letter := range x { fmt.Printf("Index : %d Value : %c \n", i, letter) }
There are two parts in a 'for range loop'.
The right part has,
Where 'x' is the actual string. And 'range' keyword says that the loop is a 'for range loop'.
And the left part has,
And what happens is, at every iteration, letters are picked from the string and kept in the 'letter' variable.
Tough to understand?
Let's simplify explaining what happens at each iteration..
So, in the first line, we have stored 'Hello' inside 'x'.
Then used the 'for range loop' to iterate it.
for i,letter := range x { fmt.Printf("Index : %d Value : %c \n", i, letter) }
And the iteration starts.
Just remember that the variable 'x', is stored in the below way.
Where, 0, 1, 2, 3, 4 and 5 are indexes. That can be used to refer each letter.
In the 1st iteration, Go finds the 'range' keyword and understands that it is a 'for range loop'.
And it finds the variable 'x', just next to 'range' keyword.
So, it takes the first letter from the 'x' variable(i.e. 'H') along with its index (i.e. '0').
And places the first letter (i.e. 'H') in the letter variable and the index (i.e. '0') in the 'i' variable.
Now, if you look at the print statement,
We have printed the index stored in variable 'i' and the first letter in variable 'letter'.
And we get the below output.
Next, we come to the second iteration.
Again the 2nd iteration, it takes the second letter from the 'x' variable(i.e. 'e') along with its index (i.e. '1').
And places the first letter (i.e. 'e') in the letter variable and the index (i.e. '1') in the 'i' variable.
Now, if you look at the print statement,
We have printed the index stored in variable 'i' and the first letter in variable 'letter'.
And we get the below output.
Similarly, in the next iterations, all the values are printed eventually.