-3

We know Go is pass by value, and the slice is pointer type, then what about the [][]int? I got this code

func add(nums [][]int) {
    nums = append(nums, []int{1,2,3})
}

It seems the nums doesn't change after this function. I got confused about the [][]int.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
S.Ye
  • 57
  • 2
  • 6
  • 3
    `[][]int` is nothing more than a slice of `[]int`. Treat it like that. You have to return the result and assign it to the original slice. – icza Feb 02 '21 at 15:25
  • 5
    There's two important details here: first, slice is *not* a pointer type; it *contains* a pointer to the underlying array, but the slice itself is *not* a pointer. This leads to the second detail, the reason why `append` returns a new value is because when it needs to resize, it must create a new backing array, and since the slice isn't actually a pointer, you need to get the new slice back which contains a pointer to the new backing array. – Adrian Feb 02 '21 at 15:27
  • 1
    always remember that `append` in Go is just like `realloc` in C. You must always use the return value. The original slice is useless after `append`. – Zan Lynx Feb 02 '21 at 15:27
  • 2
    and oh yeah, assigning to `num` does not affect the original slice because `num` is a copy of the slice, created when the function was called. – Zan Lynx Feb 02 '21 at 15:31

1 Answers1

1

Your code assigns a value to a local variable called nums.

Since nums is a local variable that is not a reference, you cannot access it from outside the scope of your function add.

If you want to change the value of nums outside the function, it has to be of a pointer type.

And you have to dereference it first, then allocate the value you want to assign to it.

func add(nums *[][]int) {
    t := append(*nums, []int{1,2,3})
    *nums = &t
}
Coconut
  • 2,024
  • 18
  • 25