Skip to main content

Arrays & Slices

Slices

Slices are an important data type in Go, giving a more powerful interface to sequences than arrays.

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.

To create an empty slice with non-zero length, use the builtin make. Here we make a slice of strings of length 3 (initially zero-valued). By default a new slice’s capacity is equal to its length; if we know the slice is going to grow ahead of time, it’s possible to pass a capacity explicitly as an additional parameter to make.

var s []string
fmt.Println("uninit:", s, s == nil, len(s) == 0)

s = make([]string, 3)
fmt.Println("emp:", s, "len:", len(s), "cap:", cap(s))

---
uninit: [] true true
emp: [ ] len: 3 cap: 3

We can set and get just like with arrays.

s[0] = "a"
s[1] = "b"
s[2] = "c"
fmt.Println("set:", s)
fmt.Println("get:", s[2])
---
set: [a b c]
get: c

Slices support a “slice” operator with the syntax slice[low:high]. For example, this gets a slice of the elements s[2], s[3], and s[4].

l := s[2:5]
fmt.Println("sl1:", l)
---
sl1: [c d e]

We can declare and initialize a variable for slice in a single line as well.

t := []string{"g", "h", "i"}
fmt.Println("dcl:", t)

The slices package contains a number of useful utility functions for slices.

Slices can be composed into multi-dimensional data structures. The length of the inner slices can vary, unlike with multi-dimensional arrays.

twoD := make([][]int, 3)
for i := 0; i < 3; i++ {
innerLen := i + 1
twoD[i] = make([]int, innerLen)
for j := 0; j < innerLen; j++ {
twoD[i][j] = i + j
}
}
fmt.Println("2d: ", twoD)

---
2d: [[0] [1 2] [2 3 4]]

Arrays

In Go, an array is a numbered sequence of elements of a specific length. In typical Go code, slices are much more common; arrays are useful in some special scenarios.

Here we create an array a that will hold exactly 5 ints. The type of elements and length are both part of the array’s type. By default an array is zero-valued, which for ints means 0s.

var a [5]int
fmt.Println("emp:", a)

---
emp: [0 0 0 0 0]

We can set a value at an index using the array[index] = value syntax, and get a value with array[index].

a[4] = 100
fmt.Println("set:", a)
fmt.Println("get:", a[4])
---
set: [0 0 0 0 100]
get: 100

The builtin len returns the length of an array.

fmt.Println("len:", len(a))
---
len: 5

Use this syntax to declare and initialize an array in one line.

b := [5]int{1, 2, 3, 4, 5}
fmt.Println("dcl:", b)

Array types are one-dimensional, but you can compose types to build multi-dimensional data structures.

var twoD [2][3]int
for i := 0; i < 2; i++ {
for j := 0; j < 3; j++ {
twoD[i][j] = i + j
}
}
fmt.Println("2d: ", twoD)
---
2d: [[0 1 2] [1 2 3]]