~/Go Slice Manipulation Techniques

Sep 11, 2025


A slice in Go is a flexible view into an array. Understanding slice manipulation helps optimize memory and improve code clarity.

Creating a slice

1
s := []int{1, 2, 3, 4, 5}

Slicing

1
t := s[1:4] // t == []int{2, 3, 4}

Appending elements

1
s = append(s, 6) // s == []int{1,2,3,4,5,6}

Documentation

Copying slices

1
2
dst := make([]int, len(s))
copy(dst, s) // [2](https://pkg.go.dev/builtin#copy)

Deleting an element

To remove the element at index 2

1
s = append(s[:2], s[3:]...)

Pattern explained

Reslicing

1
s = s[2:] // s is now [3 4 5 6]

Capacity and length

1
2
cap(s) // [returns](https://golang.org/pkg/builtin/#cap) capacity
len(s) // [returns](https://golang.org/pkg/builtin/#len) length

Use these manipulations to efficiently manage collections of data in Go.

Tags: [go] [slice] [array]