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

160 views

1

package main

import "fmt"

func main() {
    var s []int // nil slice; len=0 cap=0
    s = append(s, 1, 2, 3)
    fmt.Printf("s=%v len=%d cap=%d\n", s, len(s), cap(s))

    // append may reallocate; track capacity to see when.
    for i := 4; i <= 8; i++ {
        s = append(s, i)
        fmt.Printf("i=%d cap=%d\n", i, cap(s))
    }

    // make([]T, len, cap) pre-sizes to avoid reallocation.
    pre := make([]int, 0, 10)
    pre = append(pre, 1, 2, 3)
    fmt.Printf("pre len=%d cap=%d\n", len(pre), cap(pre))
}

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.