Go Keyword range: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
No edit summary
Line 25: Line 25:
:Note 2: <tt>range</tt> returns a ''copy'' of the value, in the same way it would pass an argument to a function. It does NOT return a reference to the element in the structure it iterates over.<br>
:Note 2: <tt>range</tt> returns a ''copy'' of the value, in the same way it would pass an argument to a function. It does NOT return a reference to the element in the structure it iterates over.<br>
</blockquote>
</blockquote>
==Iterating over Indices==
<pre>
var a [5]int
for i := range a {
  // i is the index
}
</pre>
==Iterating over Values==
<pre>
var a [5]int
for _, value := range a {
  // 'value' is the value
}
</pre>
==Iterating over Indices and Values==
<pre>
var a [5]int
for i, value := range a {
  // i is the index
  // 'value' is the value
}
</pre>


==Iterating over Key/Values in a Map==
==Iterating over Key/Values in a Map==

Revision as of 17:36, 24 August 2023

Internal

Overview

Iterating through Arrays

Iterating though Arrays

TO PROCESS

Internal

Overview

range keyword is used to iterate over strings, arrays, slices, maps, channels and variadic function arguments. It returns two values. On the first position is the index/key, and on the second position is the copy of the value in that element. For slices and arrays, range always starts to iterate from index 0. If you need more control over the start index, use a for loop.

Note 1: that only a first identifier is declared, that is the index and not the value, as the intuition would suggest. See examples below.
Note 2: range returns a copy of the value, in the same way it would pass an argument to a function. It does NOT return a reference to the element in the structure it iterates over.

Iterating over Key/Values in a Map

m := map[string]string { 
    "k1": "v1",
    "k2": "v2",
    "k3": "v3",
}

for key, value := range m {
    // 
}

range and Channels

range can be used to receive from a channel in a for loop. range blocks until a value is available on the channel. The iteration values produced are the successive values sent on the channel until the channel is closed and all values are consumed. When the channel is closed, the for loop exists:

var c chan string

for m := range c {
   // do something with the message
}

If the channel is nil, the range expression blocks forever.