range
Keyword for Iterating Over Collections
range
In Go, the range
keyword is a powerful tool used to iterate over various types of collections such as arrays, slices, maps, strings, and channels. It provides a concise and readable way to loop through elements in these data structures. Understanding how to effectively use the range
keyword can make your code more efficient and easier to understand.
range
Keyword for Iterating Over CollectionsThe range
keyword allows you to iterate over each element of an array or slice. When iterating over an array or slice, range
returns two values: the index and the element at that index.
Example: Iterating Over an Array or Slice
Outpu
In this example:
arr
, range
returns the index (0 to 4) and the corresponding value.slice
, range
works similarly, iterating over each element.When using range
to iterate over a map, it returns two values: the key and the value associated with that key. This allows you to easily access all key-value pairs in the map.
Example: Iterating Over a Ma
Output
Here, range
iterates over each key-value pair in the map person
, printing the key and its corresponding value.
Using range
with strings allows you to iterate over Unicode code points (runes) in the string. The range
expression returns the index of the character and its rune value.
Example: Iterating Over a String
Output:
In this example, range
correctly handles Unicode characters in the string "Hello, 世界," providing the index and the rune value of each character.
range
can also be used to receive values from a channel until it is closed. When iterating over a channel with range
, it retrieves each value sent on the channel and stops when the channel is closed.
Example: Iterating Over a Channel
Output:
Here, range
continues to receive values from the channel ch
until the channel is closed by the sender.
range
You can use range
to filter specific values from a slice based on a condition.
Output:
In this example, range
is used to loop through each number in the slice numbers
and filter out even numbers.
You can use range
to count the occurrences of each character in a string.
Output:
In this example, range
iterates over each character in the string text
and counts their occurrences using a map.
The range
keyword in Go is a versatile tool for iterating over collections like arrays, slices, maps, strings, and channels. It provides a concise and readable way to access elements and perform operations on them. By leveraging the range
keyword effectively, you can write more efficient and maintainable Go code. Whether you need to iterate over an array, process map keys, handle Unicode strings, or work with channels, range
offers a simple solution for iteration in Go.