![]() |
VOOZH | about |
We’re so glad you’re here. You can expect all the best TNS content to arrive Monday through Friday to keep you on top of the news and at the top of your game.
Check your inbox for a confirmation email where you can adjust your preferences and even join additional groups.
Follow TNS on your favorite social media networks.
Become a TNS follower on LinkedIn.
Check out the latest featured and trending stories while you wait for your first TNS newsletter.
Iteration is a key functionality of most programming languages. Essentially, iteration means repeating a block of code in a specific order, usually until a specific event or result occurs. You can iterate through numerous data structure types, such as arrays, slices, strings, maps and channels.
Usually, you iterate with the help of a loop, such as a for loop. Along with the for loop comes a special keyword you can use to simplify iteration through data structures. In Golang, that keyword is “range”; it provides both the index and the value of each element within the data structure throughout the iteration.
In other words, when you use the range keyword with a for loop, it iterates through all entries of the data structure and, for each entry, it assigns iteration values to the corresponding iteration variables (so long as they are present), then executes the block.
But what is the difference between a for loop with and without the range keyword? Essentially, a range clause in a for loop makes those loops cleaner and easier to read. This can be especially important when you’re first getting your feet wet with Go because for loops can get a bit complicated.
Let’s take a look at an example of a for loop that iterates through a slice.
Remember what a slice is? If not, I’ve got your back. A slice is similar to an array, with the difference being that a slice is dynamically sized, so it can grow and shrink as needed. The syntax of a slice looks like this:
slice_name := []datatype{values}
Here’s an example of what that might look like:
myslice := []int{1,2,3}
For this purpose, there are two functions you’ll want to know about: len() and cap(). The len() function returns the number of elements in the slice and the cap() function returns the number by which elements the slice can either grow or shrink.
Enough about slices — let’s get back to the for-loop example. We’ll create a for loop that iterates through a list of Linux distributions and prints them out. The code looks like this:
In the above code, we’ve initialized a slice named “distros” as a list of strings. Those strings are “Ubuntu”, “Fedora”, “Pop!_OS”, “Linux Mint”, “elementaryOS” and “openSUSE”. In our for loop, we initialize the variable i to 0, make sure that i is less than the length of the distros array, and increment i by 1 at the end of each iteration.
What if we use the range keyword for this loop?
First off, the syntax of the for-range loop looks like this:
for key, value := range collection {
// body of the loop
}
Remember the for loop above? Using the range keyword, that would change to:
for i, distros := range distros {
fmt.Println(i, distros)
}
The output for both blocks of code would be exactly the same:
0 Ubuntu
1 Fedora
2 Pop!_OS
3 Linux Mint
4 elementaryOS
5 openSUSE
As you can see, using the range keyword simplifies and cleans up the code. The difference is, the for-range loop makes it possible to access key-value pairs and even alter them.
But how? Let me show you an example. Let’s pretend we have a business with two levels of employees: junior and senior. What we want to do is give our senior employees a $10,000 bonus. We’re going to use a for-range loop to make this happen.
Let’s use two employees, Bob and Fred. They both make $100,000, but since Fred is a senior employee, he receives a $10k bonus. The first block of our code is fairly straightforward:
package main
import "fmt"
type Account struct {
Name string
Type string
Balance int
}
We now create a function that will define Bob as a junior employee making $100,000 and Fred as a senior employee making the same base salary. That portion of the code looks like this:
func main() {
acts := []Account{
{"Bob", "junior", 100_000},
{"Fred", "senior", 100_000},
}
So far, so good.
Now we’ll create a for-range loop that examines Type. If any entry is “senior”, 10,000 is added to the Balance.
for i := range acts {
if acts[i].Type == "senior" {
acts[i].Balance += 10_000
}
Here’s how the above block works:
for i := range acts: A loop that iterates over the indices of our acts collection.if acts[i].Type == "senior": Checks if the Type field of the element at index i within the acts collection equals “senior”.acts[i].Balance += 10_000: If the condition is true, the Balance field of the element is incremented at index i by 10,000.Finally, we print out the acts collection:
fmt.Println(acts)
The entire code looks like this:
If we run the above, the output is:
[{Bob junior 100000} {Fred senior 110000}]
Success! Fred received a 10K bonus. Let’s hope Bob doesn’t find out.
And that’s the basics of using the range keyword in Go. To find out more about range clauses, check out the official Go documentation.