Introduction

In the Go programming language, arrays and slices are data structures that store related ordered elements. Although both store related elements in order, they have significant differences that we are going to address below.

Arrays

  1. It has capacity defined at creation time. This allocated size cannot be changed.
  2. Element access is achieved using indexes.
  3. Element modification is done using indexes.
  4. Element count is done using len() built-in function.

Defining an array

The general schema of an array is:

[capacity] date_type {element_values}

For example

var names [3]string = [3]string{"mary", "had", "lamb"}

Will output

[mary had lamb]

You can use fmt.Printf("%q", names) to instruct the output to quote the elements:

["mary" "had" "lamb"]

Slice

It’s a mutable ordered sequence of elements.

  1. It has a variable length. Thi can be expanded or reduced as needed.
  2. Element access is achieved using indexes
  3. Element modification is done using indexes.
  4. Element count is done using len() built-in function.

Defining a slice

Similar to defining an array but without the size. The schema is

[]data_type{element_values}

If you want to create a slice of a starting size n that has no elements, you can use the make command:

names := make([]string, 3)

This will print:

["" "" ""] // default data type values, in this case empty strings

If you want to pre-allocate memory, you can add a third value to make that will allocate the capacity size:

names := make([]string, 3, 5)

This will make a zeroed slice with a length or 3 and a preallocated size of 5.

Slicing arrays into slices

Define an index range on an array to get a slice:

subNames := names[1:3]

Adding elements to a slice

Use append() builtin function to add elements to a slice:

names := []string{"hello"}
names = append(names, "world")

Append, len, cap and memory

The append function allocates memory for a slice when you use it to add elements to a slice. In some systems, this may be a perfomance bottleneck. Lets say you have a slice of ints that you want to fill using a for loop:

nums := make([]int, 5, 10)

for i := 0; i < len(nums); i++ {
    nums = append(nums, i)
}

This will fill up the nums slice with 5 integers: [0 1 2 3 4]. However, the append method has additional memory allocations.

A better idea would be to use the cap built in method in place of the len. This is because,cap give you the current capacity of the slice, unlike len that gives the number of values in the slice.

nums := make([]int, 5, 10)

for i := 0; i < cap(nums); i++ {
    nums = append(nums, i)
}

Multidimensional slices

You can have multidimensional slices like:

matrix := [][]int{{0, 0}, {1 1}}

Conclusion

We’ve seen the basics of arrays and slices and some of their inner workings.

You can comment on this article by clicking on this link.