Gopher

Array vs Slices in Golang

Published on 10 April 2020
Last Updated on 10 April 2020

What are arrays in Golang

In Golang, arrays are of a specific length that are used for storing elements in a numbered sequence. Number of an element in an array is called as element index. Array element index begin at 0.

Length of the array determines how many elements can be stored in an array.

Arrays are of fixed length and they can not be re-sized once they are initialized.

Because arrays are inflexible in nature they are less used and slices are more commonly used.

Declaring arrays in Golang

Code given below initializes a new array of a fixed length that has eight elements in it.

// initializing array of integers with custom values
var arrayOfIntegers = [8]int{1, 2, 3, 4, 5, 6, 7, 8}

Code given below demonstrates how to create a new array of string data type that has 3 elements in it.

var alphabets = [3]string{
	"a", "b", "c",
}

... is an operator used for automatic length declaration. Code given below makes use of automatic length declaration operator to let the compiler figure out what length to be used for the array.

Code

var alphabets = [...]string{
	"a", "b", "c",
}

Arrays can be multi-dimensional.

What are slices in Golang

Slices are an abstraction built on top of existing array data type.

Slices are references to existing arrays. In Golang slices are designed to act like dynamic arrays however they are just references to an existing array of a fixed length.

Slices feel like dynamic arrays however they are not dynamic arrays they are just abstractions built to feel like dynamic arrays that are built on top of existing array data type.

When a modification is made to the slice the underlying array referenced by the slice is modified.

Two slices can reference the same underlying array so if a modification is made to the first slice it will reflect on any slice that references the same array.

Components of slices in Golang

Slices in Golang may have following components:

  • Pointer to underlying array.
  • Length of the slice.
  • Capacity of the slice.
  • Slice bounds.

Declaring slices in Golang

Slices are declared just like arrays however the length of the array is omitted:

var slice3 = []string{"a", "b", "c", "d", "e", "f"}

Slices can also be created using the built in make function:

s := make([]string, 5)