Sobes.tech
Senior

How to make the unit added through append visible on the fifth line as well? Without changing the fill function's signature.

sobes.tech AI

Answer from AI

In Go, if a function fill takes a slice by value and adds an element inside using append, the outer slice will not change, because append may create a new array.

To make the unit added via append visible on the fifth line without changing the signature of fill, you can pass the slice by pointer or return a new slice from the function. But since the signature cannot be changed, you can use a slice with sufficient capacity so that append does not create a new array, and changes will be visible outside.

Example:

func fill(s []int) {
    s = append(s, 1) // if capacity is enough, the addition will modify the original array
}

func main() {
    s := make([]int, 4, 5) // length 4, capacity 5
    fill(s)
    fmt.Println(s) // now the added 1 will be visible
}

If the capacity is insufficient, append will create a new array, and changes will not be visible. Therefore, it is important that the slice's capacity is sufficient before calling fill.