๐ŸŽ“ A1Learner
๐Ÿ”

Go Slices

A slice holds a changing number of values of one type. A slice can grow as a program adds items.

A slice literal

The slice holds three numbers. The whole slice prints first and its length prints next.

package main

import "fmt"

func main() {
	nums := []int{4, 8, 15}
	fmt.Println(nums)
	fmt.Println(len(nums))
}

Make a slice with room

Make builds an empty slice with room for two items. The length is 0 and the capacity is 2.

package main

import "fmt"

func main() {
	nums := make([]int, 0, 2)
	fmt.Println(len(nums), cap(nums))
}

Take a sub-slice

The sub-slice starts at index 1. It stops just before index 3.

package main

import "fmt"

func main() {
	nums := []int{10, 20, 30, 40}
	part := nums[1:3]
	fmt.Println(part)
}

Grow with append

Append adds one item at a time. The third append grows the capacity from 2 to 4.

package main

import "fmt"

func main() {
	nums := make([]int, 0, 2)
	nums = append(nums, 7)
	nums = append(nums, 8)
	nums = append(nums, 9)
	fmt.Println(nums)
	fmt.Println(len(nums), cap(nums))
}

Example

package main

import "fmt"

func main() {
	items := make([]string, 0, 2)
	items = append(items, "pen")
	items = append(items, "book")
	items = append(items, "mug")
	fmt.Println(items)
	fmt.Println(len(items), cap(items))
}

Key points

  • A slice type names only the item type.
  • Use len to read how many items a slice holds.
  • Capacity is the room a slice has before it must grow.
  • Use cap to read the capacity of a slice.
  • Use append to add items to the end of a slice.
  • A sub-slice takes a part of a slice by two indexes.

In this example, items starts as an empty slice with room for two items. Three append calls add pen, book, and mug. The slice grows on the third append, so the length is 3 and the capacity is 4.

Note

A slice can change length, and an array cannot.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Go Playground

Exercise

What are the length and capacity of make([]int, 0, 2)?