Go Keyword range: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
No edit summary
Line 11: Line 11:
:Note that only a first identifier is declared, that is the ''index'' and not the value, as the intuition would suggest. See examples below:<br>
:Note that only a first identifier is declared, that is the ''index'' and not the value, as the intuition would suggest. See examples below:<br>
</blockquote>
</blockquote>
=Iterating over Indices=


<pre>
<pre>
var a [5]int
var a [5]int
for i, value := range a {
for i := range a {
   // i is the index
   // i is the index
}
</pre>
=Iterating over Values=
<pre>
var a [5]int
for i := range a {
  // i is the index
}
</pre>
=Iterating over Indices and Values=
<pre>
var a [5]int
for _, value := range a {
   // value is the value
   // value is the value
}
}
</pre>
</pre>

Revision as of 04:28, 28 March 2016

Internal

Overview

range keyword is used to iterate over arrays, slices, maps and variadic function arguments. It returns two values. On the first position is the index/kyes, and the second position is the value.

Note that only a first identifier is declared, that is the index and not the value, as the intuition would suggest. See examples below:

Iterating over Indices

var a [5]int
for i := range a {
   // i is the index
}

Iterating over Values

var a [5]int
for i := range a {
   // i is the index
}

Iterating over Indices and Values

var a [5]int
for _, value := range a {
   // value is the value
}