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...)
}
Flattening a slice of slices means taking a list of lists and combining them into one single list. You would use this when you have grouped data that you need to process as a continuous stream. Think of it like taking several stacks of papers and merging them into one big pile.