How to Flatten a Slice of Slices in Go

Flatten a slice of slices in Go using slices.Concat or a loop with append.

Use slices.Concat to merge a slice of slices into a single flat slice in Go 1.21 and later.

import "slices"

nested := [][]int{{1, 2}, {3, 4}, {5}}
flat := slices.Concat(nested...)

For Go versions prior to 1.21, use a loop with append:

var flat []int
for _, sub := range nested {
    flat = append(flat, sub...)
}