Clone and filter slices
Clone and filter slices
Use make and copy for independent integer storage. Filtering selects only values satisfying a condition. A new destination preserves the input; in-place filtering reuses storage but changes shared elements. Copies are shallow: nested reference-like values may still share data.
package main
import "fmt"
func main() { a := []int{1, 2, 3} b := make([]int, len(a)) copy(b, a) b[0] = 99 fmt.Println(a, b)}Each slice now has separate storage for integers. For nil input, make-based copying returns a non-nil empty slice. The standard library slices.Clone (Go 1.21+) instead preserves nilness and also makes a shallow copy.
Expected output:
[1 2 3] [99 2 3]Filter into new or existing storage
package main
import "fmt"
func main() { a := []int{3, 4, 5, 6} var evens []int for _, v := range a { if v%2 == 0 { evens = append(evens, v) } } fmt.Println(a, evens) b := a[:0] for _, v := range a { if v%2 == 0 { b = append(b, v) } } fmt.Println(a, b)}The first loop makes a separate result. The second writes at or behind the current read index, which is safe for this forward filter. Elements after len(b) remain in the array. If they contain references, clear the unused tail when you own the storage and no aliases need those values (clear requires Go 1.21+).
Expected output:
[3 4 5 6] [4 6][4 6 5 6] [4 6]Try it locally
Write positive(s []int) []int returning positive values in separate storage. Print input and result for []int{-1,3,0,5}, and result length for nil input.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Slices 08: Clone and filter slices
Check the lesson objective before moving on.
How can you make a separate copy of integer elements?
What is a risk of in-place filtering?