0

In the code below:

s4 := []int{0, 1, 2, 3, 4, 5}
sp4 := &s4
sp5 := &((*sp4)[1:])

I want to get the pointer a slice of s4[1:] as s5, but this cause an error:

cannot take the address of (*sp4)[1:]

But if I write like this:

s4 := []int{0, 1, 2, 3, 4, 5}
sp4 := &s4
s5 := (*sp4)[1:]
sp5 := &s5

It works!

I have made some tests, and found that when I change *sp5, s4 change as while. That's what I just need.

But why cannot I write sp5 := &((*sp4)[1:])?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
pingze
  • 973
  • 2
  • 9
  • 18
  • 3
    Some things in Go are literally _unaddressable_: You simply cannot take their address because the language spec _forbids_ it. – Volker Mar 13 '19 at 12:59
  • 3
    This: `(*sp4)[1:]` is a slice expression, it results in a slice value. This value may not have a memory address as it is not in a variable, it may just live in processor registers until you store it in a variable. To give the compiler the freedom to store it wherever it sees best, the spec does not allow taking its address. – icza Mar 13 '19 at 13:01

0 Answers0