Pointer to slice element


(Elber Kam) #1

I am wondering if it is possible to get a pointer to a slice element.
Following code:

type Val struct{ key string }
vals := make([]Val, 2)
vals[0] = Val{"A"}
vals[1] = Val{"B"}
ptr := &vals[0]
println(ptr.key)
vals[0] = Val{"C"}
println(ptr.key)

prints A C
It makes sense because we got pointer to first slot of the slice. Is there any way to get pointer to first element of slice without copying?


(Elber Kam) #2

It makes sense what is happening. So we got pointer to slot 0, then this address is overwritten with new Item, so address of slot 0 has this new item.
We can mark this as resolved.