- Why can’t receivers be a pointer type?
Thanks Brian. It sounds like golang made it illegal to define methods on a defined pointer type for readability/disambiguation reasons rather than some fundamental, underlying technical issue. Frankly the confusion it eliminates still isn’t entirely clear to me. Given that names in general don’t confer whether something is a variable, type or interface, there are plenty of opportunities for confusion, so why single this one out? "Because you can" may be the answer. Lack of experience is likely the biggest obstacle in my understanding. I'm hopeful it’ll become more obvious along the way. I appreciate your insights.
On Sat, Feb 27, 2021 at 9:12 PM Howard Waterfall <hwate...@gmail.com> wrote:
>
> Thanks Ian! Some comments inline.
Please write to the mailing list, not just to me. Thanks.
> Given that PrefixPtr is defined:
>
> type PrefixPtr *Prefix
>
> I'm not seeing how this:
>
> func (rec PrefixPtr) outputString(s string)
>
> is any more ambiguous than this:
>
> func (rec *Prefix) outputString(s string)
In the latter, the method is clearly associated with Prefix, and
applies to addressable values of type Prefix. In the former, it's not
clear whether the method applies to addressable values of type Prefix.
One could make an argument either way.
> It's definitely possible that I'm being pig headed tho! Is it the asterisk that makes it clear it's a pointer?
>
>>
>> > Why isn’t *Prefix considered a pointer type?
>>
>> It is, but a method defined with a receiver type of *Prefix is a
>> pointer method of Prefix. That method can be called on any value of
>> type *Prefix and also on any addressable value of type Prefix.
>
>
> My question arose from the error that was generated:
>
> ./receiver.go:24:6: invalid receiver type PrefixPtr (PrefixPtr is a pointer type)
>
>
> It seems to suggest that receivers can't be a pointer type. Since an error isn't generated with *Prefix, I inferred it wasn't considered a pointer type.
You can't define a method on a defined pointer type. You can define a
method on a pointer to a defined non-pointer type.
Ian