Behavior to copy the value of pointer inside another pointer

91 views
Skip to first unread message

Olivier Szika

unread,
Aug 4, 2021, 11:18:07 AM8/4/21
to golang-nuts
Hi all,

I am surprised by the behavior of "&(*var)".


It is expected?

burak serdar

unread,
Aug 4, 2021, 11:25:39 AM8/4/21
to Olivier Szika, golang-nuts
On Wed, Aug 4, 2021 at 9:18 AM Olivier Szika <szika....@gmail.com> wrote:
Hi all,

I am surprised by the behavior of "&(*var)".

According to the language spec, pointer indirection is addressable:


Thus, taking the address of an indirection yields the original pointer, not a pointer to a copy of its contents.
 
--
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...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/5f265699-ed67-4798-92d0-88832a7444d1n%40googlegroups.com.

Axel Wagner

unread,
Aug 4, 2021, 11:28:53 AM8/4/21
to Olivier Szika, golang-nuts
Yes. From the spec:

For an operand x of pointer type *T, the pointer indirection *x denotes the variable of type T pointed to by x.

Emphasis mine. "The variable", means it really denotes the storage location that `x` points to. Not the value or anything like that. Further, then:

For an operand x of type T, the address operation &x generates a pointer of type *T to x. The operand must be addressable, that is, either a variable, pointer indirection, or slice indexing operation; or a field selector of an addressable struct operand; or an array indexing operation of an addressable array. As an exception to the addressability requirement, x may also be a (possibly parenthesized) composite literal.
 
Emphasis mine, again. This tells you that the behavior of `&` with composite literals to allocate a new variable is an exception - in general, `&` just gives you the address of whatever expression you apply it to. In this case, specifically, a pointer-indirection denoting, as we've seen above, the variable that x points to.

So, it is completely expected that `&(*p) == p`.

--

Olivier Szika

unread,
Aug 4, 2021, 11:31:07 AM8/4/21
to golang-nuts
Oh Yes,

Thanks!

Reply all
Reply to author
Forward
0 new messages