What are slices in go? How are they better when compared to arrays?

Quick tech learn
2 min readAug 22, 2023

--

Slices are beneficial data types in Go when compared to arrays. They build on arrays to provide great power and convenience.

A slice in go can be implemented by two ways as follows,

//Method 1
var s []string

//Method 2
s = make([]string, 5)

First method is creating a normal variable as others using “var” keyword.

Second method, you can use is built-in make() method. For this you need three arguments, datatype, length, capacity.

However, capacity is not required, first two arguments are alone enough. By default a new slice’s capacity is equal to its length.

Unlike arrays, slices are typed only by the elements they contain (not the number of elements). An uninitialized slice equals to nil and has length 0.

The advantages of slices over arrays are,

  1. Arrays are immutable but slices are mutable.
  2. Arrays have fixed size but slices can be resized. It can be achieved by using built-in append function.
s = append(s, "d")
s = append(s, "e", "f")

While appending, if the capacity of the slice reached its threshold, a new memory with the double the current capacity will be allocated and a pointer to the new slice will be returned to s. So, s shouldn’t be discarded.

3. Slices can also be copied. This can be done by using copy() function.

c := make([]string, len(s))
copy(c, s)

4. When arrays are passed to any functions, a copy of the array is passed. But when you pass a slice, the underlying array it is passed as an reference. So editing the slice will change the original array itself.

Although slices have added advantages over arrays in go, they too have some disadvantages which will covered in this blog.

--

--

Quick tech learn

Blogs are written by a fullstack developer with experience in tech stack like golang, react, SQL, mongoDB and cloud services like AWS