Sobes.tech
Senior

func main() { a := make([]int, 0, 3) a = append(a, 1) a = append(a, 2) add(a) fmt.Printf("%v", a) // } func add(a []int) { a = append(a, 3) a = append(a, 4) }

sobes.tech AI

Answer from AI

In this example, the slice a is created with length 0 and capacity 3. Elements 1 and 2 are added in main, then the function add(a) is called. Inside add, elements 3 and 4 are added to the slice a, but this is a local copy of the slice passed by value.

In Go, slices are structures containing a pointer to an array, length, and capacity. When passing a slice to a function, the slice structure is copied, but not the underlying array. Changes to the array elements inside the function are visible outside, but operations that change the slice's length (like append), which modify the slice structure, will not affect the slice in the caller unless a new slice is returned or a pointer is passed.

In this case, add modifies a local copy of the slice but does not return it, so in main, the slice a remains [1 2].

Example output:

[1 2]

If you want changes in add to be visible in main, you can:

  • Return a new slice from add and assign it in main.
  • Pass a pointer to the slice.

Example with return:

func add(a []int) []int {
    a = append(a, 3)
    a = append(a, 4)
    return a
}

func main() {
    a := make([]int, 0, 3)
    a = append(a, 1, 2)
    a = add(a)
    fmt.Printf("%v", a) // [1 2 3 4]
}
func main() { a := make([]int, 0, 3) a = append(a, 1)… - sobes.tech