Help understanding slices, variable arguments, and passing slices to functions

81 views
Skip to first unread message

Andrew Pillar

unread,
Sep 25, 2023, 7:57:23 AM9/25/23
to golan...@googlegroups.com
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

Jan Mercl

unread,
Sep 25, 2023, 8:12:47 AM9/25/23
to Andrew Pillar, golan...@googlegroups.com
On Mon, Sep 25, 2023 at 1:57 PM Andrew Pillar <m...@andrewpillar.com> wrote:

A nice discussion of slices can be found for example here:
https://research.swtch.com/godata

tl;dr: Yes, slices are passed by value (everything in Go is passed by
value), but a slice does not contain the backing array, only a pointer
to it.

-j
Reply all
Reply to author
Forward
0 new messages