Golang: Slice

By Xah Lee. Date: . Last updated: .

What is Slice

Slice is like Array but length can be changed. (Golang slice is essentially a reference to a segment of array. )

Syntax of Slice Type

Syntax for slice type is

[]type

with each slot of type type.

Example: var x []int, declare a variable x of int slice type.

〔see Golang: Basic Types

package main

import "fmt"

func main() {

	// declare var of type slice
	var ss []int

	// print the type
	fmt.Printf("%T", ss) // []int

}

Literal Expression of Slice

[]type{v1, v2, etc}

package main

import "fmt"

func main() {

	var xslice = []int{9, 2, 6}

	fmt.Printf("%v\n", xslice) // [9 2 6]
	fmt.Printf("%T\n", xslice) // []int

}

Create slice with “make”

make([]type, n)

Create a slice of n number of slots of type type, with default values of nil.

〔see Golang: Zero Value

n can be 0.

make([]type, n, capacity)
  • With capacity of capacity number of slots.
  • capacity defaults to the value of n.

💡 TIP: capacity is not necessary, because golang automatically grow the slice capacity when you append(args) beyond the capacity. However, capacity is there for efficiency reasons. Because, every time the slice grows beyond capacity, golang has to create new and copy whole, and this is slow. Best to always create a slice with expected max of items.

package main

import "fmt"

func main() {

	// 3 slots of int
	var xx = make([]int, 3)
	fmt.Println(xx) // [0 0 0]

	// 3 slots of int, capacity of 9
	var yy = make([]int, 3, 9)
	fmt.Println(yy) // [0 0 0]
}

Length

len(s)

Return the length of slice s.

Capacity

cap(s)

Return the capacity.

Golang, array and slice

Golang, data structure