I have some code whereby I am iterating over some data, putting that
data into a buffer slice defined outside the loop, then passing the
contents of that buffer slice to a function which returns a struct
containing that data. See the playground link as a stripped down
demonstration of what I'm actually doing:
https://go.dev/play/p/66Ynp7W2TQ8
With the above example, the code outputs,
[1 2 3]
[1 2 3]
instead of what I would expect, which would be,
[0 1 2]
[1 2 3]
I have two fixes for this. The first would be to move the buf slice
inside the most outer loop so that a new buffer slice is created on
each iteration. The other is to allocate a new tmp slice within the
MakeValues function and to copy the contents of a to that tmp slice and
use that in the Args struct parameter.
My initial understanding of slices in Go, is that they are passed by
value to functions, so a copy of the slice's contents should be given
to the MakeValues function in this case, yet the observed behaviour
indicates that this is not the case?
As stated, I have a solution to my issue, I would just like to better
understand the semantics of slices and how they are passed to
functions. And what the best approach to take for my situation would
be, whereby I am using a temporary buffer slice that is cleared after
each iteration for storing data to then pass somewhere else.
- Andrew
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit
https://groups.google.com/d/msgid/golang-nuts/ede82dfcca6e43062309440727800e15533d0c8f.camel%40andrewpillar.com.