SoFunction
Updated on 2025-03-04

Detailed explanation of how to use data structures in Go in Go

introduction

Arrays are powerful data structures that store similar types of data. You can identify and access elements within it through indexes.

In Golang you can use the use of the variable i by initializing the variable i at 0 and increasing the variable until it reaches the length of the array.forLoop the array.

Their syntax looks like this:

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

For example, let's loop 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++ {
		(numbers[i])
	}
}

In the above code, we define a name callednumbersarray of integers and initialize variablesiLoop them. Then, we're addingiprint out the values ​​of each index of the array at the same time.

The above code output is as follows:

7
9
1
2
4
5

We can also userangeThe keyword loops through the array, which iterates over the entire length of the array.

The syntax is as follows:

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 {
		(index, a)
	}
}

In the above code, we define an array of strings and usefor..rangeThe keyword loops its index and value.

for...rangeThe syntax is simpler and easier to understand. You use iterate over different data structures such as arrays, strings, maps, slices, etc.

This outputs the following:

0 a
1 b
2 c
3 d
4 e
5 f

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

For example:

package main
import (
	"fmt"
)
func main() {
	arr := []string{"a", "b", "c", "d", "e", "f"}
	for _, a := range arr {
		(a)
	}
}

In the above code, we modified the previous example and translated theindexReplace the variable with an underscore. We do this to ignore the index, but to output elements of the array.

This outputs the following:

a
b
c
d
e
f

How to loop strings in Go

Strings in programming are immutable—which means you cannot modify them after you create them. They are an ordered sequence of one or more characters (such as letters, numbers, or symbols) and can be constants or variables.

In Golang,StringUnlike other languages ​​such as Python or JavaScript. They are expressed asUTF-8 byte sequence, each element in the string represents a byte.

You usefor...rangeLoop or loop the string using a regular loop.

For example:

package main
import (
	"fmt"
)
func main() {
	word := "Ab$du"
	for index, a := range word {
		(index, string(a))
	}
}

In the above code, we define a string containing different characters and loop through its entries. Strings are represented as bytes in Golang, which is why when printing out we need to convert each value to a typestring

This output:

0 A
1 b
2 $
3 d
4 u

If we do not convert each entry into a string, Golang prints out the byte representation.

For example:

package main
import (
	"fmt"
)
func main() {
	word := "Ab$du"
	for index, a := range word {
		(index, a)
	}
}

result:

0 65
1 98
2 36
3 100
4 117

We can also use the regularfor loopto iterate over the string.

package main
import (
	"fmt"
)
func main() {
	word := "ab$du"
	for i := 0; i < len(word); i++ {
		(i, string(word[i]))
	}
}

How to loop map structure in Go

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

You can usefor...rangeStatements iterate in Golangmap, where it gets 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 {
		(key, val)
	}
}

In the above code, we define a map that stores it as typestringis a key, typeintDetails of the bookstore as its value. Then, we usefor..rangeKeywords loop through their keys and values.

There is no specified order in iterating maps in Golang, and we should not expect keys to be returned in the order defined when we loop.

This code outputs:

physics 3
maths 5
biology 9
chemistry 6

If we don't want to specify a value and just return a key, we don't define the value variable at all, but only the key variable.

For example:

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

This outputs the following:

maths
biology
chemistry
physics

Similarly, if we are not interested in the map's keys, we use underscores to ignore the keys and define variables 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 {
		(val)
	}
}

This output:

5
9
6
3

How to loop Struct in Go

Struct is a data structure in Golang that combines different data types into one. Unlike arrays, structures can contain integers, strings, booleans, etc. - all of which are concentrated in one place.

Unlike maps, we can easily loop through its keys and values, in Golang, you need to use areflectpackage. This allows us to modify objects of any type.

For example, let's create a structure and loop 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 := (ubay)
	types := ()
	for i := 0; i < (); i++ {
		((i).Index[0], (i).Name, (i))
	}
}

This output:

0 Name John
1 Age 17
2 Gender Female
3 Single false

In the above code, we define a name calledPersonofstruct, has different properties and created thestructnew instance of . Then, we usereflectPackage to getstructandtypevalue.

By using regularityforloop, we add initialization variablesi, until it reaches the length of the structure.

We useNumFieldMethod to get the total number of fields in the structure.(i).IndexMethod returns the index of each key in the structure.(i).NameMethod returns the field name of each key in the structure. and(i)Returns the value of each key in the structure.

in conclusion

In this article, we explore how to iterate different data types in Golang. For more information about Golang iterative loop data structure, please pay attention to my other related articles!