CopyExplicitDeref gets a pointer to the struct in its receiver. If you
have a pointer to T, then taking a pointer to the dereferenced T is a
no-op: you get the pointer of the thing you just dereferenced. Any
statement &*whatever will always yield the value of whatever. Copy
happens on assignment, and no assignment occurs in this statement.

CopyImplicitDeref does not get a pointer to the struct in its
receiver; it gets a copy. The pointer returned will not be equal to
the original pointer as you've returned a pointer to the copy the
receiver got.

Your latest example dereferences t and copies it into a new variable.
Because an assignment happens between the dereference and address-of
operators, you've created a copy and thus a new object. You then
return a pointer to this copy.

All these behaviors are desired and expected.

--dho


2018-03-28 9:29 GMT-07:00 thwd <sedeveloper...@gmail.com>:
> Even more surprising, make this small change to the previous playground link
> code:
>
> func (t *T) CopyExplicitDeref() *T {
> x := *t
> return &x
> }
>
> Merely introducing a local variable changes the behavior of the method.
>
> On Wednesday, March 28, 2018 at 6:21:49 PM UTC+2, thwd wrote:
>>
>> https://play.golang.org/p/pjyoPX99Zr1
>>
>> Taking the address of an explicit dereference has different behavior than
>> implicitly dereferencing and taking address.
>>
>> Is this the desired behavior? It surprised me.
>
> --
> 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+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

-- 
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+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to