Iteration in Golang – How to Loop Through Data Structures in Go

In programming, iteration (commonly known as looping) is a process where a step is repeated n number of times until a specific condition is met.

Just like every other programming language, Golang has a way of iterating through different data structures and data types like structs, maps, arrays, strings, and so on.

In this article you will learn:

  • How to loop through arrays
  • How to loop through strings
  • How to loop through maps
  • How to loop through structs

How to Loop Through Arrays and Slices in Go

Arrays are powerful data structures that store similar types of data. You can identify and access the elements in them by their index.

In Golang, you can loop through an array using a for loop by initialising a variable i at 0 and incrementing the variable until it reaches the length of the array.

They syntax is shown below:

复制代码
for i := 0; i < len(arr); i++ {
    // perform an operation
}

As an example, let's loop through an array of integers:

复制代码
package main

import (
    "fmt"
)

func main() {
    numbers := []int{7, 9, 1, 2, 4, 5}

    for i := 0; i < len(numbers); i++ {
        fmt.Println(numbers[i])

    }
}

In the code above, we defined an array of integers named numbers and looped through them by initialising a variable i . We then printed out the value of each index of the array while incrementing i .

The code above outputs the following:

复制代码
7
9
1
2
4
5

We can also loop through an array using the range keyword which iterates through the entire length of an array.

The syntax is shown below:

复制代码
for index, arr := range arr {
  // perform an operation   
}

For example:

复制代码
package main

import (
    "fmt"
)

func main() {
    arr := []string{"a", "b", "c", "d", "e", "f"}

    for index, a := range arr {
        fmt.Println(index, a)
    }

}

In the code above, we defined an array of strings and looped through both its index and value using the for..range keyword.

The for...range is more simpler in syntax and easier to understand. You use it to iterate different data structures like arrays, strings, maps, slices, and so on.

This outputs the following:

复制代码
0 a
1 b
2 c
3 d
4 e
5 f

Assuming we were to ignore the index and simply print out the elements of the array, you just replace the index variable with an underscore.

For example:

复制代码
package main

import (
    "fmt"
)

func main() {
    arr := []string{"a", "b", "c", "d", "e", "f"}

    for _, a := range arr {
        fmt.Println(a)
    }

}

In the code above, we modified the previous example and replaced the index variable with an underscore. We did this to ignore the index and output the elements of the array instead.

This outputs the following:

复制代码
a
b
c
d
e
f

How to Loop Through Strings in Go

Strings in programming are immutable -- this means you can't modify them after you create them. They're ordered sequences of one or more characters (like letters, numbers, or symbols) that can either be a constant or a variable.

In Golang, strings are different from other languages like Python or JavaScript. They are represented as a UTF-8 sequence of bytes and each element in a string represents a byte.

You loop through strings using the for...range loop or using a regular loop.

For example:

复制代码
package main

import (
    "fmt"
)

func main() {
    word := "Ab$du"

    for index, a := range word {
        fmt.Println(index, string(a))
    }
}

In the code above, we defined a string containing different characters and looped through its entries. Strings are represented as bytes in Golang, which is why we needed to convert each value to the type string when printing them out.

This outputs:

复制代码
0 A
1 b
2 $
3 d
4 u

If we hadn't converted each entry to a string, Golang would print out the byte representation instead.

For example:

复制代码
package main

import (
    "fmt"
)

func main() {
    word := "Ab$du"

    for index, a := range word {
        fmt.Println(index, a)
    }
}

The outputs:

复制代码
0 65
1 98
2 36
3 100
4 117

We can also iterate through the string by using a regular for loop.

复制代码
package main

import (
    "fmt"
)

func main() {
    word := "ab$du"

    for i := 0; i < len(word); i++ {
        fmt.Println(i, string(word[i]))
    }
}

How to Loop Through Maps in Go

In Golang, a map is a data structure that stores elements in key-value pairs, where keys are used to identify each value in a map. It is similar to dictionaries and hashmaps in other languages like Python and Java.

You can iterate through a map in Golang using the for...range statement where it fetches the index and its corresponding value.

For example:

复制代码
package main

import (
    "fmt"
)

func main() {
    books := map[string]int{
        "maths":     5,
        "biology":   9,
        "chemistry": 6,
        "physics":   3,
    }
    for key, val := range books {
        fmt.Println(key, val)
    }
}

In the code above, we defined a map storing the details of a bookstore with type string as its key and type int as its value. We then looped through its keys and values using the for..range keyword.

Iterating through a map in Golang doesn't have any specified order, and we shouldn't expect the keys to be returned in the order we defined when we looped through.

This code outputs:

复制代码
physics 3
maths 5
biology 9
chemistry 6

If we don't want to specify the values and return just the keys instead, we simply don't define a value variable and define a key variable only.

For example:

复制代码
package main

import (
    "fmt"
)

func main() {
    books := map[string]int{
        "maths":     5,
        "biology":   9,
        "chemistry": 6,
        "physics":   3,
    }
    for key := range books {
        fmt.Println(key)
    }
}

This outputs the following:

复制代码
maths
biology
chemistry
physics

Likewise, if we aren't interested in the keys of a map, we use an underscore to ignore the keys and define a variable for the value.

For example:

复制代码
package main

import (
    "fmt"
)

func main() {
    books := map[string]int{
        "maths":     5,
        "biology":   9,
        "chemistry": 6,
        "physics":   3,
    }
    for _, val := range books {
        fmt.Println(val)
    }
}

This outputs:

复制代码
5
9
6
3

How to Loop Through Structs in Go

Struct is a data structure in Golang that you use to combine different data types into one. Unlike an array, a struct can contain integers, strings, booleans and more -- all in one place.

Unlike a map, where we can easily loop through its keys and values, looping through a struct in Golang requires that you use a package called reflect. This allows us you modify an object with an arbitrary type.

For example, let's create a struct and loop through it:

复制代码
package main

import (
    "fmt"
    "reflect"
)

type Person struct {
    Name   string
    Age    int
    Gender string
    Single bool
}

func main() {
    ubay := Person{
        Name:   "John",
        Gender: "Female",
        Age:    17,
        Single: false,
    }
    values := reflect.ValueOf(ubay)
    types := values.Type()
    for i := 0; i < values.NumField(); i++ {
        fmt.Println(types.Field(i).Index[0], types.Field(i).Name, values.Field(i))
    }
}

This outputs:

复制代码
0 Name John
1 Age 17
2 Gender Female
3 Single false

In the code above, we defined a struct named Person with different attributes and created a new instance of the struct. We then used the reflect package to get the values of the struct and its type.

By using the regular for loop, we incremented the initialised variable i until it reached the length of the struct.

We use the NumField method to get the total number of fields in the struct. The types.Field(i).Index method returns the index of each key in a struct. The types.Field(i).Name method returns the field name for each key in the struct. And the values.Field(i) returns the value for each key in the struct.

Conclusion

In this article, we have explored how to perform iteration on different data types in Golang.

While you can loop through arrays, maps, and strings using a for loop or for..range loop, structs require an additional package called reflect to loop through their keys and values.
© 著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务

喜欢的朋友记得点赞、收藏、关注哦!!!

相关推荐
爱地球的曲奇10 分钟前
arcgispro双击打开没反应怎么办
经验分享·学习·arcgis
Yan_ks39 分钟前
JAVA面向对象——对象和类的基本语法
java·开发语言
罗政40 分钟前
springboot+vue实现服装商城系统(带用户协同过滤个性化推荐算法)
vue.js·spring boot·推荐算法
虾球xz41 分钟前
游戏引擎学习第289天:将视觉表现与实体类型解耦
c++·学习·游戏引擎
广州华锐视点1 小时前
AR 开启昆虫学习新视界,解锁奇妙微观宇宙
学习·ar
小Tomkk1 小时前
2025年PMP 学习二十三 16章 高级项目管理
学习·pmp
Paddy哥1 小时前
jsmpeg+java+ffmpeg 调用摄像头RTSP流播放
java·开发语言·ffmpeg
等什么君!1 小时前
学习vue3:监听器
前端·vue.js·学习
老李不敲代码1 小时前
榕壹云上门家政系统:基于Spring Boot+MySQL+UniApp的全能解决方案
spring boot·mysql·微信小程序·小程序·uni-app
oioihoii1 小时前
C++23 新增扁平化关联容器详解
java·开发语言·c++23