VOOZH about

URL: https://thenewstack.io/how-golang-range-simplifies-data-structure-iteration/

⇱ How Golang Range Simplifies Data Structure Iteration - The New Stack


TNS
SUBSCRIBE
Join our community of software engineering leaders and aspirational developers. Always stay in-the-know by getting the most important news and exclusive content delivered fresh to your inbox to learn more about at-scale software development.
REQUIRED
It seems that you've previously unsubscribed from our newsletter in the past. Click the button below to open the re-subscribe form in a new tab. When you're done, simply close that tab and continue with this form to complete your subscription.
The New Stack does not sell your information or share it with unaffiliated third parties. By continuing, you agree to our Terms of Use and Privacy Policy.
Welcome and thank you for joining The New Stack community!
Please answer a few simple questions to help us deliver the news and resources you are interested in.
REQUIRED
REQUIRED
REQUIRED
REQUIRED
REQUIRED
Great to meet you!
Tell us a bit about your job so we can cover the topics you find most relevant.
REQUIRED
REQUIRED
REQUIRED
REQUIRED
REQUIRED
Welcome!

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.

What’s next?

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.

PREV
1 of 2
NEXT
VOXPOP
As a JavaScript developer, what non-React tools do you use most often?
Angular
0%
Astro
0%
Svelte
0%
Vue.js
0%
Other
0%
I only use React
0%
I don't use JavaScript
0%
Thanks for your opinion! Subscribe below to get the final results, published exclusively in our TNS Update newsletter:
NEW! Try Stackie AI
From clobbered drafts to real-time sync
Apr 14th 2026 10:00am, by David Moore
TypeScript 6.0 RC arrives as a bridge to a faster future
Mar 14th 2026 9:00am, by Darryl K. Taft
Mastra empowers web devs to build AI agents in TypeScript
Jan 28th 2026 11:00am, by Loraine Lawson
2024-05-10 17:00:14
How Golang Range Simplifies Data Structure Iteration
Go

How Golang Range Simplifies Data Structure Iteration

The Go language's for loop comes with a special "range" keyword that provides the index and value of each element within an iteration of a data structure.
May 10th, 2024 5:00pm by Jack Wallen
👁 Featued image for: How Golang Range Simplifies Data Structure Iteration
Feature image via Unsplash.

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},
   }
  • Name: Bob or Fred
  • Type: junior or senior
  • Balance: 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:

  1. for i := range acts: A loop that iterates over the indices of our acts collection.
  2. if acts[i].Type == "senior": Checks if the Type field of the element at index i within the acts collection equals “senior”.
  3. 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.

TRENDING STORIES
Jack Wallen is what happens when a Gen Xer mind-melds with present-day snark. Jack is a seeker of truth and a writer of words with a quantum mechanical pencil and a disjointed beat of sound and soul. Although he resides...
Read more from Jack Wallen
SHARE THIS STORY
TRENDING STORIES
SHARE THIS STORY
TRENDING STORIES
TNS DAILY NEWSLETTER Receive a free roundup of the most recent TNS articles in your inbox each day.
The New Stack does not sell your information or share it with unaffiliated third parties. By continuing, you agree to our Terms of Use and Privacy Policy.