Skip to Content
🎉 Wiki 1.0.0 is finally here!.
GolangGo Slices

Go Slices

Slices are a type of array that can be resized.

var name string

Dynamic Variable Declaration

name := "John"

Creating a Slice

slice := []int{1, 2, 3}

Creating a Slice with a Capacity

slice := make([]int, 0, 10)

Adding Elements to a Slice

slice = append(slice, 4)

Removing Elements from a Slice

slice = slice[:len(slice)-1]

Getting the Length of a Slice

Length is the number of elements in the slice.

len(slice)

Getting the Capacity of a Slice

Capacity is the maximum number of elements that the slice can hold.

cap(slice)

If we append an element to a slice that exceeds the capacity, the slice will be resized to double the current capacity.

slice = append(slice, 4)

Resizing a Slice

slice = slice[:len(slice)+1]

Concatenating Slices

slice = slice[:len(slice)+1]

Iterating over a Slice

for _, value := range slice { fmt.Println(value) }

Sorting a Slice

sort.Slice(slice, func(i, j int) bool { return slice[i] < slice[j] })

Finding the Index of an Element in a Slice

index := sort.Search(len(slice), func(i int) bool { return slice[i] == element })

Removing an Element from a Slice

slice = append(slice[:index], slice[index+1:]...)

Removing an Element from a Slice by Value

slice = append(slice[:index], slice[index+1:]...)
Last updated on