Understanding Arrays and Slices in Golang

Understanding Arrays and Slices in Golang

In Golang (Go, for short), arrays and slices are fundamental data structures that allow developers to efficiently store and manage collections of data. Although, both data structures have many similarities, it is important to understand their differences and practical use cases in order to prevent misuse and allow your code to be more robust.

This article will explore the key features, syntax and best practices for working with arrays and slices in Golang.

Arrays in Golang

An array is a data structure that allows you to store a fixed number of elements of the same data type. In Golang, you cannot modify the size of an array after declaring it. This behaviour makes it rigid to work with but it also has its advantages.

Because the size of an array is fixed, it only need to allocate memory once. Other data types with dynamic or varying lengths will need to dynamically allocate memory based on the current size of the array. This behaviour means arrays are efficient to use in terms of memory.

Declaring an Array in Golang

In Golang, you declare an array with this syntax:

// using the var keyword
var arrayName = [length of the array]<datatype of elements in the array>{element1, element2}

// using the shorthand
arrayName := [length of the array]<datatype of elements in the array>{element1, element2}

The above is the syntax to follow when declaring an array in Go. Here is an example of an array:

package main

import "fmt"

func main() {
    var myArray = [5]int{1, 2, 3, 4, 45}
    fmt.Println(myArray)

    myArray1 := [3]int{3, 4, 3} // Amorim ball!
    fmt.Println(myArray1)
}

The code above declares two arrays of integers. The first one can contain five integer elements while the second one can contain only three. If you run the code above, you should get this result:

[1 2 3 4 45]
[3 4 3]

You can define an array of strings if you want:

package main

import "fmt"

func main() {
    var dogBreeds = [5]string{"American Bully", "Golden Retriever", "German Shepherd", "Labrador Retriever", "French Bulldog"}
    fmt.Println(dogBreeds)

}

In any of the examples above, attempting to include a data type different from the one specified will result in an error for you.

Accessing Elements in an Array

Like other programming languages, you can access the elements in a Golang array by using their indexes. Indexes in Golang start from 0. The following example shows you how to access elements in an array:

package main

import "fmt"

func main() {
    var myArray = [5]int{1, 2, 3, 4, 45}
    fmt.Println(myArray[4]) // prints the last element in the array
    fmt.Println(myArray[0]) // prints the first element in the array
}

Updating Arrays in Golang

In Go, it is possible to update the values of the elements inside an array, but there are rules to doing this:

  1. You cannot change the data type of the element you want to update.

  2. You cannot add an element to an array if it will exceed the specified length of the array.

  3. You cannot add a new element to an array if it has a different data type from the one specified when declaring the array.

To update elements in an array, you need to use the index. Here is an example:

package main

import "fmt"

func main() {
    var myArray = [5]int{1, 2, 3, 4, 45}
    fmt.Println(myArray[4]) // prints the last element in the array
    fmt.Println(myArray[0]) // prints the first element in the array

    myArray[4] = 100 // replace an integer with an integer
    fmt.Println(myArray[4]) // prints 100
}

The code above replaces the value of the element with the fourth index in the array.

Initializing an Array in Golang

In programming, you initialize a variable the first time you assign a value to it. In Golang, when you declare a variable without assigning a value to it, it automatically takes the default value for its data type.

You can declare an array without initializing it. Here is an example:

numbers := [5]int{} //not explicitly initialized

If you print the array above, you will get this result:

[0 0 0 0 0]

Although the numbers array had no value, it assigned the zero value of integers to the five elements expected to fill up the space.

In Golang, when you do not initialize an array, the default values of the items in it will be the zero values of the specified data type.

Tip: The zero value for integers is 0. The zero value for strings is an empty quote (““)

When initializing an array, you are not required to add values for all the indexes immediately. You can partially initialize an array. Here is an example:

package main

import "fmt"

func main() {
    myArray := [5]int{1, 28}
    fmt.Println(myArray)
}

If you run the code above, you will get this result:

[1 28 0 0 0]

You can assign the other values later in your code.

In Golang, it is possible for you to initialize specific indexes when you declare an array. Here is an example:

package main

import "fmt"

func main() {
    myArray := [5]int{1: 10, 4: 40}
    fmt.Println(myArray)
}

In the code above, the first and fourth indexes of the array are given values. The code can be intepreted like this:

  1. 1:10 means: assign the value 10 to the first index

  2. 4:40 means: assign the value 40 to the fourth index

If you run the code above, you will get the following:

[0 10 0 0 40]

From the output, it is obvious that the first and fourth indexes were initialized while the other elements defaulted to their zero values.

Slices in Golang

Slices in Go are similar to arrays. However, they are more powerful and more dynamic than arrays. A slice does not have a fixed number of elements. It can increase and decrease based on your code requirements.

Like arrays, slices can only contain elements of the same data type.

There are multiple ways to create a slice in Go. They are listed below:

  • Using the []datatype of slice{values} format

  • Create a slice from an array

  • Using the make() function

Creating a Slice in Golang With the []datatype of slice{values} Format

To create a slice with this method, you need to follow the syntax below:

slice := []datatype{values}

Here is a simple example:

mySlice := []string{"Car", "Apple"}
fmt.Println(mySlice)

The code above will return this:

[Car Apple]

The length of the slice can be as long as you want it to be.

Creating a Slice From an Array

In Golang, it is possible to create a slice from a previously existing array. Here is an example:

package main

import "fmt"

func main() {
    myArray := [5]int{1, 2, 3, 4, 45}
    fmt.Println(myArray)
    mySlice := myArray[2:4]
    fmt.Println(mySlice)
}

The code above creates a slice from the second index to the fourth index, excluding the value on the fourth index. If you run thhe code, you should get the following:

[1 2 3 4 45]
[3 4]

The second line of the output above is a slice.

Creating a Slice With the make() Function in Golang

The third method to create a slice is by using the built-in make() function in Go. This is the syntax:

slice_name := make([]datatype, length, capacity)

The length and capacity of a slice will be explained in the next section but it is important to note that if you don’t specify a capacity when using the make() function, the default value will be the length of the slice. This example shows you how to create a slice with the make() function:

package main

import "fmt"

func main() {
    mySlice := make([]int, 5, 10)
    fmt.Println(mySlice)

}

The code above will initialize a sice with zero values:

[0 0 0 0 0]

You can assign actual values to each element and even add more than 5 elements to the slice as your code progresses.

The Length and Capacity of a Slice in Golang

In Go, the length of a slice refers to the total amount of elements that are inside the slice currently. It is the number of elements that you can access. You can find the length of a slice by using the len() function:

fmt.Println(len(mySlice))

On the other hand, the capacity of a slice is the amount of space reserved in memory for the slice to grow. A slice can have a length of six and a capacity of ten. This means four more elements can fit into the slice. Once the capacity of your slice is used up, Go reallocates memory to create space for more elements to fit.

You can determine the capacity of a slice with the cap() method:

fmt.Println(cap(mySlice))

Conclusion

Arrays and slices are very powerful data structures in Go. You will need to use them multiple times in your projects. It is important that you keep learning about their similarities and differences so you can make better decisions when using them. If you enjoyed the article, you can ping me on X!