On Sunday, December 17, 2017 at 2:32:24 PM UTC-6, jlfo...@berkeley.edu 
wrote:

>
> Here's something that someone new to Go might run up against. I know I did.
>
>
Me, too! 

The trivial program below, derived from "The Go Programming Language"
> book, shows two methods that differ only in the way they treat their
> receiver. In the first, the receiver is a pointer to a slice, and in the
> second, the receiver is a slice. So far so good. What confused me is
> that both methods return the same result even when called the same way.
> I would have expected only one of the methods to work.
>
>
I never really figured out what was going on, but I finally just accepted 
it as "go is doing
what I want it to do, even if I say it wrong." 

Here's what I believe is the explanation. The book says (slightly
> edited) "If the receiver p is a variable of type Path but the method
> requires a *Path receiver, we can use this shorthand:
>
> p.pr1()
>
> and the compiler will perform an implicit &p on the variable.". This
> explains what happens when pr1() is called.
>
>
Right. I guess this all works because there are so few things you can do 
with pointers; so this
isn't going to create odd ambiguities.
 

> I'm surprised that Go would include this implicit behavior because type
> conversions are generally required to be explicit.
>
>
I agree that it seems un-Go-like initially. But the more I think about it, 
the more it makes sense given
other restrictions on pointers. The only thing you can do with pointers is 
pass them and
deferences them. You never actually do anything with the value of the 
pointer itself. A type can have
methods, but a pointer to a type can't. So it's always(?) going to be safe 
for the compiler to do this.

Of course you don't want people using both forms within a local scope. So 
that is my guess at
why the this "shortcut" is allowed only via receivers.

I am, of course, speculating wildly. I would be pleased to be set straight 
by the people who actually
know what is going on.

And I pray to whatever is holy that I never take the habits I'm picking up 
with this back to C.

-j

-- 
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