-1

I am new go golang. I find go seems to pass by reference in below's recursive code:

package main

import "fmt"

func main(){
    var res [][]int
    tracing(&res, []int{111})
    fmt.Println("res is: ", res)
}


func tracing(res *[][]int, l []int) {
    if len(l) > 1 {
        fmt.Println(l, " has been added to res")
        *res = append(*res, l)
        return
    }
    for i := 0; i < 2; i ++ {
        l = append(l, i)
        tracing(res, l)
        l = l[:len(l) - 1]
    }
}

Below is the resulting output:

[111 0]  has been added to res
[111 1]  has been added to res
res is:  [[111 1] [111 1]]

As we all know, go is pass by value. So what I expect is to have [111 1] and [111 1] in res.

But it seems like the l has been changed outside of the function, as the for loop seems to have an impact on recursive calls.

Why does it happen?

Is it because of some sort of memory escape? Like the l somehow escaped from stack to heap?

fredpan
  • 45
  • 1
  • 9
  • So the reason why append can resolve this question is because the append actually reallocate the backing array at all time? – fredpan May 16 '22 at 03:06

0 Answers0