Sobes.tech
Junior — Middle

Is it possible to add elements to a list passed as an argument to a function?

sobes.tech AI

Answer from AI

Yes, you can add elements to a slice passed to a function, but it's important to understand that a slice in Go is a structure containing a pointer to an array, a length, and a capacity.

If you use append inside a function and assign the result to a local variable, the changes will not affect the original slice outside the function unless you return the new slice or pass a pointer to the slice.

Example:

func addElement(s []int) []int {
    s = append(s, 42) // add element
    return s
}

func main() {
    s := []int{1, 2, 3}
    s = addElement(s) // need to assign back
    fmt.Println(s) // [1 2 3 42]
}

If you want to modify the slice inside a function without returning it, you can pass a pointer:

func addElementPtr(s *[]int) {
    *s = append(*s, 42)
}

func main() {
    s := []int{1, 2, 3}
    addElementPtr(&s)
    fmt.Println(s) // [1 2 3 42]
}