Ad space (banner)
๐ŸนGo Lessons
Lesson 42 / 68

Flattening a Slice

In this lesson you will learn how to flatten a nested slice in Go, combining append with variadic expansion. This is for anyone searching for "Go slice flatten implementation".

Expanding a slice that contains other slices into one flat slice is called flattening. You implement it by combining append with ... (variadic expansion).

The sample code has flatten() take a nested [][]int and append each inner slice, expanded, into one result with result = append(result, inner...). Adding ... is what spreads the slice's contents as individual values.

A common stumbling block for beginners is forgetting the ... and trying to append the inner slice itself as a single element. You need to recognise when expansion is required and when it is not.

In real-world development this idea applies whenever you want to treat nested data as one list, including collapsing multi-level tree data into a single list.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Go directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)