Golang Slice Examples

These Go examples use slices and the append method. A slice is a versatile and linear collection of elements.

Slices. In Go, slices are used throughout programs.

They are easier to use (and faster to run) than arrays. Slices have underlying arrays.

 

 

Declare slices. A slice has no size as part of its type. And with built-in methods like cap() and append() we can test and mutate slices.

 

 

Append. This example creates a slice of strings. It initially has three elements. We then use the append built-in to add two more strings to the slice.

 

Result: The slice contains all five elements. A slice is an expandable, resizable array.

Based on:

Golang 1.4

Golang program that uses append on slice

package main

import "fmt"

func main() {
    elements := []string{"cat", "dog", "bird"}
    elements = append(elements, "fish", "snake")
    fmt.Println(elements)
}

Output

[cat dog bird fish snake]

Cap, capacity. A slice has an underlying array. This array has a capacity (a size). This is the number of elements that the slice can hold before being resized.

Cap: The cap() built-in tells us the internal allocation heuristics of a slice. When it runs out of room, a slice's array doubles in size.

Here: We create a slice of three elements. Its cap is 3. We then add a fourth element, and its capacity doubles to 6.

Golang program that uses cap, measures capacity of slice

package main

import "fmt"

func main() {
    elements := []int{100, 200, 300}

    // Capacity is now 3.
    fmt.Println(cap(elements))

    // Append another element to the slice.
    elements = append(elements, 400)

    // Capacity is now 6—it has doubled.
    fmt.Println(cap(elements))
}

Output

3
6

Len, length. The len built-in returns the element count of a slice. An empty slice has a length of 0. This is not the same as capacity—only existing elements are counted.

Golang program that uses len on slice

package main

import "fmt"

func main() {
    // Create an empty slice.
    // ... Its length is 0.
    items := []string{}
    fmt.Println(len(items))

    // Append a string and the slice now has a length of 1.
    items = append(items, "cat")
    fmt.Println(len(items))
}

Output

0
1

Loop, range. With the range keyword we can loop over a slice. The value returned on each iteration is the index into the slice. We can access an element with it.

Golang program that loops over slice

package main

import "fmt"

func main() {
    animals := []string{"bird", "dog", "fish"}

    // Loop over the slice.
    for v := range animals {
	fmt.Println(animals[v])
    }
}

Output

bird
dog
fish

Loop, iteration. A three-part for-loop can be used to iterate over a slice. We start at 0 and continue while the index is less than the length of the slice (found with len).

For

Golang program that uses for-loop on slice

package main

import "fmt"

func main() {
    colors := []string{"blue", "yellow", "orange"}

    // Loop over all indexes with a three-part for-loop.
    for v := 0; v < len(colors); v++ {
	fmt.Println(colors[v])
    }
}

Output

blue
yellow
orange

Make. With this method we can create slices of a type and size. Internally slices must be initialized, and the make() method does this for us.

The built-in function make(T, args) serves a purpose different from new(T). It creates slices, maps, and channels only, and it returns an initialized (not zeroed) value of type T.

Effective Go: golang.org

Arguments: The first argument to make() is the type of the slice. The second argument is the length of elements. The third is the capacity.

Capacity: The capacity of a slice can be set as a performance optimization to avoid future allocations. A slice resizes automatically.

Golang program that uses make to create slice

package main

import "fmt"

func main() {
    // Create a slice of 5 integers.
    values := make([]int, 5)

    // Assign some elements.
    values[0] = 100
    values[4] = 200

    // Loop over elements in slice and display them.
    for v := range values {
	fmt.Println(values[v])
    }
}

Output

100
0
0
0
200

Remove duplicates. A slice may contain duplicate values. But some times in a program we want to remove these. We can use a map to eliminate duplicates.

Remove Duplicates

 

Idiomatic Go. The term "idiomatic" refers to languages. An idiomatic usage is one that sounds natural and is easy to understand. Idiomatic Go uses slices. We emphasize them over arrays.