Go Keyword range: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
No edit summary
 
Line 9: Line 9:
{{Internal|Go_Slices#Iterating_through_Slices|Iterating through Slices}}
{{Internal|Go_Slices#Iterating_through_Slices|Iterating through Slices}}
=Iterating over Map Keys and Values=
=Iterating over Map Keys and Values=
{{Internal|Go_Maps#Iterating_over_Map_Keys_and_Values|Iterating over Map Keys and Values}}
{{Internal|Go_Maps#Iterating_over_a_Map|Iterating over Map Keys and Values}}


=TO PROCESS=
=TO PROCESS=

Latest revision as of 00:00, 27 August 2024

Internal

Overview

range can be used to iterated through channels.

Iterating through Arrays

Iterating though Arrays

Iterating through Slices

Iterating through Slices

Iterating over Map Keys and Values

Iterating over Map Keys and Values

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 {
    // 
}