Y
Y
Yermek2020-07-15 10:29:54
go
Yermek, 2020-07-15 10:29:54

Why doesn't the closure work?

There is this test:

func fn(got []string) func(string) {
  return func(input string) {
    got = append(got, input)
  }
}

func TestWalk(t *testing.T) {
  cases := getCases()
  for _, test := range cases {
    t.Run(test.Name, func(t *testing.T) {
      var got []string
      walk(test.Input, fn(got))

      if !reflect.DeepEqual(got, test.ExpectedCalls) {
        t.Errorf("got %v, want %v", got, test.ExpectedCalls)
      }
    })
  }
}


If in the 10th line I write
walk(test.Input, func(input string) {
                got = append(got, input)
                  })

then the tests run fine.

As I understand it, slices are passed by reference, the returned anonymous function in `fn` has access to `got`. Explain, please :-)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Tikhonov, 2020-07-15
@ermek6

Because not by reference, but by value . Those. the length, capacity, and pointer to slice data are copied, but the data itself is not.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question