loading...

Golang Tutorial - 5 Array, Slice and Map

nadirbasalamah profile image nadirbasalamah ・7 min read

Golang Tutorial (10 Part Series)

1) Golang tutorial - 1 Introduction 2) Golang tutorial - 2 Constant 3 ... 8 3) Golang tutorial - 3 Control Flow (Selection) 4) Golang tutorial - 4 Control Flow (Iteration) 5) Golang Tutorial - 5 Array, Slice and Map 6) Golang tutorial - 6 Function 7) Golang tutorial - 7 struct and interface 8) Golang tutorial - 8 Error Handling 9) Golang tutorial - 9 Concurrency using goroutine 10) Golang Tutorial - 10 Concurrency with channel

In programming, storing multiple values or data can be done using data structure. Data structure is a "container" that can be used to store multiple data or values. The examples of data structure in Go are array, slice and map.

Array

Array is a data structure that can store multiple values with the same type and using certain size. Array isn't recommended to be used but it's good to know the characteristics of array in Go. Because using certain size, the size or length can't be changed automatically.
The anatomy of array declaration is like this:

//[size of array]data type{values}
data := [5]int{1, 2, 3, 4, 5}

Adding data into array can be done using certain index like this:

//declaring empty array
data := [2]int{}
data[0] = 1 //assign data "1" into index 0
data[1] = 2 //assign data "2" into index 1

Notice that accessing or assigning data from the beginning of array started from index 0.
If the number of data inserted is larger than array's size or length. It throw an error.
For example:

//declaring empty array
data := [2]int{}
data[0] = 1
data[1] = 2
data[2] = 3 //throw an error : invalid array index 2 (out of bounds for 2-element array)

To accessing each data from array can be done using for loop.
Using regular for loop is like this:

data := [5]string{"NodeJS", "PHP", "Python", "Go", "Java"} //declare an array of string
for i := 0; i < len(data); i++ {  //len(data) is used to get the length of array
    fmt.Println(data[i]) //access data from index " i "
}

The output :

NodeJS
PHP
Python
Go
Java

From that code, there is len(data) syntax, it is a method that can be used to get the size or length of array or slice.
Using for range loop is like this:

data := [5]string{"NodeJS", "PHP", "Python", "Go", "Java"} //declare an array of string
//retrieve "v" (value) from array, ignore index using " _ " notation
for _, v := range data {
    fmt.Println(v)
}

The output same with the above.
Using fmt.Println can be used also to check the values stored inside array.

data := [5]string{"NodeJS", "PHP", "Python", "Go", "Java"} //declare an array of string
fmt.Println(data)

Output :

[NodeJS PHP Python Go Java]

Slice

Slice is a data structure that works like array but has a flexible size or length. The declaration syntax of slice is similiar with array but size or length isn't needed.

//[]data type{values}
data := []int{1, 2, 3, 4, 5}

The data can be stored must have a same type just like array, the slice has a feature to select certain data that needed.
Slice can be created using make() method. This method takes 3 arguments. The first argument is the type of slice, the second is the length of slice and last argument is the capacity of slice.
The example is like this:

//declare a slice of int using make method
//the length of slice is 3
//the capacity of slice is 6
data := make([]int, 3, 6)
//default items is based on data type's default value
// the default value of int is 0
//so this code print out [0 0 0]
fmt.Println("default items:", data)

//inserting some items
data[0] = 1
data[1] = 2
data[2] = 3
fmt.Println(data)
fmt.Println("Length of slice: ", len(data))
fmt.Println("Capacity of slice: ", cap(data))

data = append(data, 4, 5, 6) //insert new items

fmt.Println(data)
fmt.Println("Length of slice: ", len(data))
fmt.Println("Capacity of slice: ", cap(data))

//this insertion will increase the capacity 2x (two times)
data = append(data, 7)
fmt.Println("Length of slice: ", len(data))
fmt.Println("Capacity of slice: ", cap(data))

Based on the code above. The length of slice defines a number of items that available in slice. The capacity of slice defines a number of items that can be inserted. If the length of slice is larger than the capacity. The capacity will increased 2 times if we use make() method to create a slice.
The declaration of multiple dimension slice is also possible. For example we can declare a 2D slice like this:

//declare a slice of []int
data := [][]int{
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9},
}
//retrieve the items from slice using nested loops
for _, v := range data {
    for _, val := range v {
        fmt.Print(val)
    }
    fmt.Println("")
}

To select or slicing certain data from a slice. Use the syntax like this:

//name of the slice followed by [ start index : end index]
data[1:3]

Here it is the example, this code select or slicing certain value from slice called "data" and stored inside new slice called "newData".

data := []int{8, 9, 10, 11, 12, 13}
//selecting certain data
//name of the slice followed by [ start index : end index]
newData := data[1:3]
fmt.Println(newData)

The output :

[9 10]

The mechanism of slicing a data from slice looks like this :
Slicing a slice

The another example of slicing a data in slice is like this :

  • data[1:] means select data or values from index 1 until the last index
  • data[:4] means select data from first index until index 4. (data stored in index 4 isn't included).

Adding data into slice can be done using append() method. This method use 2 input which is the slice and the data that need to be added. The usage is like this:

//declare a slice
cars := []string{"Nissan Skyline GT-R R34", "Honda NSX", "Toyota Supra", "Mazda RX-7"}
//append new data "Subaru Impreza WRX STI 22b"
cars = append(cars, "Subaru Impreza WRX STI 22b")

The full example can be seen in this code:

//declare a slice
cars := []string{"Nissan Skyline GT-R R34", "Honda NSX", "Toyota Supra", "Mazda RX-7"}
fmt.Println("Before: ", cars)
//append new data "Subaru Impreza WRX STI 22b"
cars = append(cars, "Subaru Impreza WRX STI 22b")
fmt.Println("After: ", cars)

Output:

Before:  [Nissan Skyline GT-R R34 Honda NSX Toyota Supra Mazda RX-7]
After:  [Nissan Skyline GT-R R34 Honda NSX Toyota Supra Mazda RX-7 Subaru Impreza WRX STI 22b]

Removing certain data in slice can be used also with append() with another approach. Let’s see the example:

Input: [12,13,14,15,16,17]
Output: [12,13,16,17] //remove 14 and 15

Based on that case, the steps are :

  1. Take the first two items in slice {12,13}
  2. Append data from index 4 until last index {16,17} to {12,13} The full example is like this:
data := []int{12, 13, 14, 15, 16, 17}
fmt.Println("Before removed: ", data)
/**
The steps are:
1. Take the first two items in slice {12, 13}
2. Append data from index 4 until last index {16,17} to {12,13}
**/
data = append(data[:2], data[4:]...)
fmt.Println("After removed: ", data)

The output:

Before removed:  [12 13 14 15 16 17]
After removed:  [12 13 16 17]

Notice that there is ... operator inside append() method in data[4:]... syntax. It means that retrieve all items from certain slice (this works like spread operator in JavaScript). The ... operator very useful to used together with the append() function.
If ... isn't used, the syntax looked like this:

data = append(data[:2],16,17)

Map

Map is a data structure with key-value pairs mechanism. Each item must has a unique key. The declaration of map in Go looks like this:

//  map[key type]value type
data := map[string]string{
    "BMW":        "3.0 CSL",
    "Porsche":    "911",
    "Volkswagen": "Scirocco",
}

To access or retrieve an item inside map, we can use the key that stored.

//access an item from "data" map with "BMW" as a key
data["BMW"]

If we try to retrieve an item with key that isn't found inside map, the code doesn't throw any errors. Otherwise, returns an empty item.
Adding new item in map can be done by define a key and value that want to be stored inside map. For example we want to add new item into "data" map with key and value specified like this:

data["RUF"] = "CTR"

To retrieve all items from map, there are 2 ways:

  • Using regular fmt.Println(). This way is suitable for checking the items that stored inside map.
  • Using for range loop. This way is suitable for doing any operation with items that stored inside map. Here it is the example.
//declare a map with key type is a string and value type is a string
data := map[string]string{
    "BMW":        "3.0 CSL",
    "Porsche":    "911",
    "Volkswagen": "Scirocco",
}
//add new item into map
data["RUF"] = "CTR"
//retrieve all items from map with for range loop
for k, v := range data {
    fmt.Println("Brand: ", k, "\tCar Name: ", v)
}

The output.

Brand:  BMW     Car Name:  3.0 CSL
Brand:  Porsche         Car Name:  911
Brand:  Volkswagen      Car Name:  Scirocco
Brand:  RUF     Car Name:  CTR

Removing an item from map can be done using delete() method followed by map name and item's key. The example is like this:

data := map[string]string{
    "BMW":        "3.0 CSL",
    "Porsche":    "911",
    "Volkswagen": "Scirocco",
}
//remove an item inside map called "data" with key = "Volkswagen"
delete(data, "Volkswagen")

The usage of multi dimensional values are available in Map. the usage is like this:

//declare a map with string as a key that stored a value with type a slice of int
scores := map[string][]int{
    "Firstname":{9,8,9},
    "Lastname":{7,6,5},
    "Surname":{8,8,8}
}

Notes

  • Array is rarely used in Go programming. Array can be used to store multiple values with the exact size. So the size wouldn't change.
  • Slice is commonly used in Go programming. Slice can be used to store multiple values or items with enhanced features like selecting certain data.
  • Map is also commonly used. Map can be used to store multiple values with specified key.
  • Learn more about Array, Slice and Map in here

I hope this article helpful for helping to learn the Go programming language. If you have any thoughts or feedbacks, you can write it in the discussion section below.

Golang Tutorial (10 Part Series)

1) Golang tutorial - 1 Introduction 2) Golang tutorial - 2 Constant 3 ... 8 3) Golang tutorial - 3 Control Flow (Selection) 4) Golang tutorial - 4 Control Flow (Iteration) 5) Golang Tutorial - 5 Array, Slice and Map 6) Golang tutorial - 6 Function 7) Golang tutorial - 7 struct and interface 8) Golang tutorial - 8 Error Handling 9) Golang tutorial - 9 Concurrency using goroutine 10) Golang Tutorial - 10 Concurrency with channel

Posted on Jun 4 by:

nadirbasalamah profile

nadirbasalamah

@nadirbasalamah

A guy who interested in web development and software engineering

Discussion

markdown guide