Sobes.tech
Junior — Senior

How to keep the original slice unchanged when using append

livecode

Task condition

It is necessary to ensure that the parameter src in the function foo does not modify the original slice arr, despite the call to append.

package main

import "fmt"

func foo(src []int) {
    src = append(src, 5)
}

func main() {
    arr := []int{1, 2, 3} // len 3, cap 3
    src := append([]int(nil), arr[:1]...) // len 1, cap 1 — copy the slice

    foo(src)

    fmt.Println(src) // 1
    fmt.Println(arr) // 1 2 3
}