Go Keyword range: Difference between revisions
Jump to navigation
Jump to search
Line 43: | Line 43: | ||
=<tt>range</tt> and Channels= | =<tt>range</tt> and Channels= | ||
<tt>range</tt> can be used to read from a channel in a <tt>for</tt> loop. <tt>range</tt> 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. When the channel is closed, the <tt>for</tt> loop exists: | <tt>range</tt> can be used to [[Go_Channels#Reading_an_Instance_from_the_Channel_in_a_for_Loop|read from a channel]] in a <tt>for</tt> loop. <tt>range</tt> 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. When the channel is closed, the <tt>for</tt> loop exists: | ||
<pre> | <pre> |
Revision as of 01:58, 4 April 2016
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.
- 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 _, value := range a { // 'value' is the value }
Iterating over Indices and Values
var a [5]int for i, value := range a { // i is the index // 'value' is the value }
range and Channels
range can be used to read 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. 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.