Slices/arrays explained: create, index, slice, iterate

yourbasic.org/golang
A sliced orange

Basics

A slice doesn’t store any data, it just describes a section of an underlying array.

Construction

var s []int                   // a nil slice
s1 := []string{"foo", "bar"}
s2 := make([]int, 2)          // same as []int{0, 0}
s3 := make([]int, 2, 4)       // same as new([4]int)[:2]
fmt.Println(len(s3), cap(s3)) // 2 4

Slicing

a := [...]int{0, 1, 2, 3} // an array
s := a[1:3]               // s == []int{1, 2}        cap(s) == 3
s = a[:2]                 // s == []int{0, 1}        cap(s) == 4
s = a[2:]                 // s == []int{2, 3}        cap(s) == 2
s = a[:]                  // s == []int{0, 1, 2, 3}  cap(s) == 4

You can also create a slice by slicing an existing array or slice.

s := []int{0, 1, 2, 3, 4} // a slice
s = s[1:4]                // s == []int{1, 2, 3}
s = s[1:2]                // s == []int{2} (index relative to slice)
s = s[:3]                 // s == []int{2, 3, 4} (extend length)

When you slice a slice, the indexes are relative to the slice itself, not to the backing array.

Iteration

s := []string{"Foo", "Bar"}
for i, v := range s {
    fmt.Println(i, v)
}
0 Foo
1 Bar

Append and copy

Stacks and queues

The idiomatic way to implement a stack or queue in Go is to use a slice directly. For code examples, see

Go step by step

Core Go concepts: interfaces, structs, slices, maps, for loops, switch statements, packages.

Share this page: