Passing []int through a channel

Hi!
I’m trying to pass a slice []int through a channel from a go routine, and I’m having really weird results maybe someone here with more experience can help me. Here is the link to go playground:

https://play.golang.org/p/4fRRjfvGky

https://play.golang.org/p/d_DPINF_-B

Thanks a lot!! can you tell me what was wrong? I don’t understand why those changes fixed the problem.

In your code “ch <- out” is writing a slice value pointing to the same backing array for each iteration. The values in the backing array are being replaced by the next ‘i’ value before they can be read. You’re seeing that there’s roughly 2 iterations before the runtime scheduler swaps from sendSlices() back to main() and executes a couple iterations of the “v := sendSlices()” loop.

To be safe, you need a unique backing array for each slice.

Thanks a lot again, that was a very good explanation!

I miss wrote - “the runtime scheduler swaps from sendSlices() back to main()” should have read “the runtime scheduler swaps from the go routine back to main()”. [But you get the idea.]

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.