Go Snippet

Go Slice Operations Cheat Sheet

Difficulty: Easy

Slices are Go's dynamic array: a (pointer, length, capacity) header pointing into a backing array. This snippet covers the common operations: `append` and capacity growth, `copy` between slices, reslicing pitfalls (sharing the backing array), and a clean way to delete an element from the middle. Understand the header model and surprising slice aliasing bugs become obvious.

Code Snippets
/

Go Slice Operations Cheat Sheet

Go Slice Operations Cheat Sheet

Slices are Go's dynamic array: a (pointer, length, capacity) header pointing into a backing array. This snippet covers the common operations: `append` and capacity growth, `copy` between slices, reslicing pitfalls (sharing the backing array), and a clean way to delete an element from the middle. Understand the header model and surprising slice aliasing bugs become obvious.

Go
Easy
3 snippets
go-slices
data-structures
implementation

159 views

1

append(slice, vals...) returns a possibly-new slice header; if the backing array still has capacity it reuses it, otherwise it allocates a new one (typically doubling). Always reassign the result, since otherwise the new header is dropped on the floor. The capacity-vs-length distinction matters when chains of slices share the same backing array (next accordion). Pre-allocate with make([]T, 0, capacity) when you know roughly how many elements you will append; this is one of the easiest performance wins in Go.