Built-in Data Structures in Go with Examples

Last updated Oct 13, 2021

In this Go tutorial series we are going to learn about Data structures. Data structure is a component that can be used to store many data. Not only that, data structure can be used to solve many problems. There are many built-in data structures in Go including array, slice and map.

 

Array

Array is a data structure that has a fixed size. This is the basic syntax to create an array.

[size]data_type{}

Array is illustrated in this picture below.

Array Illustration

 

How do i create array of integers in Go Lang?

In this example, the array of integers is created.

package main

import "fmt"

func main() {
    // create an array of integers
    var myArr [3]int = [3]int{1, 2, 3}

    // access the item at index 1
    fmt.Println("Item at index 1: ", myArr[1])

    // change the item at index 2
    myArr[2] = 6

    fmt.Println("all items")

    // show all items inside array
    // using for range
    for _, item := range myArr {
        fmt.Println(item)
    }
}

Output

Item at index 1:  2
all items
1
2
6

Based on the code above, the array of integers is created in myArr variable. The item at index 1 is accessed then printed out. The item at index 2 is changed then all the items inside array is shown using for range.

 

Slice

Slice is a data structure that similar with array but has a flexible size. This is the basic syntax to create a slice.

[]data_type

The slice can be created by using make() function.

make([]data_type, size)

 

In this example, the slice of strings is created.

package main

import "fmt"

func main() {
    // create a slice of strings
    var courses []string = []string{"Data Science", "Algorithm", "Computer Network", "Database Design"}

    // access the item at index 2
    fmt.Println("Item at index 2: ", courses[2])

    // change the item at index 1
    courses[1] = "Algorithm with Java"

    // add new item with append() function
    courses = append(courses, "Machine Learning")

    // show all items inside slice
    // using for range
    fmt.Println("All courses")
    for _, course := range courses {
        fmt.Println(course)
    }
}

Output

Item at index 2:  Computer Network
All courses
Data Science
Algorithm with Java
Computer Network
Database Design
Machine Learning

 

Based on the code above, the slice of strings is created called courses. The item at index 2 is accessed then the item at index 1 is changed. The new item is added with append() function then all items is shown using for range.

In slice, some items can be selected using slicing operation. The slicing operation is illustrated in this picture below.

 

Slicing operation in go

 

In this example, the slicing operation is used to select the items from index 1 to index 3.

package main

import "fmt"

func main() {
    // create a slice of strings
    var langs []string = []string{"Go", "Java", "NodeJS", "PHP", "Python"}

    // select the items from index 1 to index 3
    // then store these items in selected variable
    var selected []string = langs[1:3]

    // show all selected items
    fmt.Println("Selected items")

    for _, item := range selected {
        fmt.Println(item)
    }
}

Output

Selected items
Java
NodeJS

 

Based on the code above, the item from index 1 to index 3 is selected.

 

How do i Remove item from slice in go lang

The item inside slice can be removed. This is the example of item removal in slice.

package main

import "fmt"

func main() {
    // create a slice of integers
    var nums []int32 = []int32{12, 32, 45, 66, 77}

    // remove item at index 2
    nums = append(nums[:2], nums[3:]...)

    // show all items after removed
    fmt.Println("after removed at index 2")
    for _, num := range nums {
        fmt.Println(num)
    }
}

Output

after removed at index 2
12
32
66
77

Based on the code above, there are many steps to remove an item at index 2.

  • Select the items from the beginning until index 2, because item at index 2 will be removed.

  • Select the items from index 3 until the last index.

  • Combine these selected items using append() function.

Notice that, in the nums[3:]... syntax there is a ... operator. This operator is used to spread or pick all items from slice. This operator works similar with spread operator in JavaScript.

The item removal mechanism in slice is illustrated in this picture below.

Slice item removal in go lang

 

How do i create multi dimensional slice with go lang?

The multi dimensional slice can be created. In this example, the multi dimensional slice is created.

package main

import "fmt"

func main() {
    // create a multi dimensional slice
    var nums [][]int = [][]int{
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9},
    }

    // multiply each item inside slice by 3
    // using nested for range
    for _, items := range nums {
        for _, item := range items {
            item *= 3
            // print out the item that is multiplied
            fmt.Println(item)
        }
    }
}

Output

3
6
9
12
15
18
21
24
27

 

Map

Map is a data structure that can be used to store key value pairs. The map data structure is illustrated in this picture below.

 

Map in Go lang

 

This is the basic syntax to create a map.

map[key_type]value_type

In this example, the map is created.

package main

import "fmt"

func main() {
    var data map[string]string = map[string]string{
        "name":    "nathan mckane",
        "address": "fairhaven",
        "email":   "nathan@mail.com",
    }

    // get the item with key equals name
    fmt.Println("name: ", data["name"])

    // change the value for email
    data["email"] = "nathan@rvwest.com"

    // print out all values from map
    fmt.Println("values from map")
    for key, val := range data {
        fmt.Println(key, ": ", val)
    }
}

Output

name:  nathan mckane
values from map
address :  fairhaven
email :  nathan@rvwest.com
name :  nathan mckane

Based on the code above, the map is created in data variable with key type is string and value type is string. The value from name key is accessed. The value from email key is changed. The all values from map is printed out using for range.

The value inside map can be removed using delete() function. In this example, the value is removed inside map.

package main

import "fmt"

func main() {
    var data map[string]string = map[string]string{
        "name":    "nathan mckane",
        "address": "fairhaven",
        "email":   "nathan@mail.com",
    }

    // the value with key equals address is removed
    delete(data, "address")

    fmt.Println("after address is removed")
    for key, val := range data {
        fmt.Println(key, ": ", val)
    }
}

Output

after address is removed
email :  nathan@mail.com
name :  nathan mckane

Based on the code above, the delete() function is used with map name and key that will be removed.

In this example, the map is used to store a frequency from each letters or characters in string.

package main

import (
    "fmt"
    "strings"
)

func main() {
    // create a sample string
    var text string = "this is sample text"

    // split the string
    var letters []string = strings.Split(text, "")

    // create a map
    // to store many frequencies from each letter inside string
    var frequencies map[string]int = map[string]int{}

    // calculate the frequency for each letter
    for _, letter := range letters {
        // calculate for valid only letter
        if letter != " " {
            frequencies[letter] = getFrequency(letters, letter)
        }
    }

    // print out the frequency from each letter
    fmt.Println("frequencies")
    for key, val := range frequencies {
        fmt.Println(key, ": ", val)
    }
}

// create a function to calculate frequency
// for certain letter
func getFrequency(letters []string, char string) int {
    var result int = 0

    for _, letter := range letters {
        if letter == char {
            result++
        }
    }

    return result
}

Output

frequencies
h :  1
s :  3
a :  1
m :  1
l :  1
t :  3
p :  1
e :  2
x :  1
i :  2

 

Conclusions

  • Array is suitable to store many items with fixed size.

  • Slice is suitable to store many items with flexible size.

  • Map is suitable to store many key value pairs.

I hope this article is helpful to learn built-in data structures in Go Programming Language.

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

577 Views