Indexing indirect slices?

69 views
Skip to first unread message

Nevin Flanagan

unread,
Dec 9, 2010, 9:52:38 AM12/9/10
to golang-nuts
I'm using a stack frame structure where several call descriptors refer
to portions of the same backing store using slices. For convenience, I
want to be able to keep a reference to the slice representing the
uppermost (current) stack frame, but since I also may need to modify
its length, I'm obliged to keep it as a pointer to the slice, rather
than as another slice.

For some reason, Go will not allow you to use an index operation on a
pointer to a slice a la (&slice)[0], even though it will allow you to
do so on a pointer to an array, or to use selection on a pointer to a
struct (a feature I adore). Is there a compelling reason for this
prohibition, and if it's an oversight, could it be corrected?

Nevin

jnml

unread,
Dec 9, 2010, 9:59:21 AM12/9/10
to golang-nuts
On 9 pro, 15:52, Nevin Flanagan <ne...@playsmith.net> wrote:
> For some reason, Go will not allow you to use an index operation on a
> pointer to a slice a la (&slice)[0], even though it will allow you to
> do so on a pointer to an array
Did you mean (*pslice)[0]?

Nevin Flanagan

unread,
Dec 9, 2010, 10:11:36 AM12/9/10
to golang-nuts
> Did you mean (*pslice)[0]?

That's the language you're obliged to use if you want to index a slice
from a pointer. I'd like to be able to use something like

arr := [...]int{1, 2, 3}
sl := arr[:]
parr := &arr
psl := &sl
fmt.Print(parr[0] == psl[0])

Right now, parr[0] is a legal index operation, but psl is a compile
error, for reasons I do not yet understand.

Rob 'Commander' Pike

unread,
Dec 9, 2010, 11:09:27 AM12/9/10
to Nevin Flanagan, golang-nuts
Go used to do this for you, but it was a holdover from the early days,
before slices. Once slices, a reference type, went in, it seemed
safer to remove the feature so programmers were clear about when they
just needed reference semantics vs. when they really needed a pointer
to a slice. Too many folks were confused about the issue and passing
pointers to slices when they had no reason to.

-rob

Nevin Flanagan

unread,
Dec 9, 2010, 12:09:39 PM12/9/10
to golang-nuts
I'm pretty clear on this by now, but I guess I'll stick with selecting
the stack from the pointer to the current call descriptor, rather than
keeping a pointer directly to the current stack.
Reply all
Reply to author
Forward
0 new messages