On Sat, Feb 27, 2021 at 7:03 PM Deiter <hwaterf...@gmail.com> wrote: > > Go: go1.15.8 darwin/amd64 > OS: MacOS 11.2.1 > > The program here includes a type and a method that acts on that type: > > type Prefix struct { > prefix string > } > > func (rec *Prefix) outputString(s string) { > fmt.Printf("%v: %v\n", rec.prefix, s) > } > > Very straightforward. I expected that this would work too: > > type PrefixPtr *Prefix > func (rec PrefixPtr) outputString(s string) { > fmt.Printf("%v: %v\n", rec.prefix, s) > } > > But it led to: > # receiver > ./receiver.go:24:6: invalid receiver type PrefixPtr (PrefixPtr is a pointer > type) > ./receiver.go:30:10: prefixer.outputString undefined (type PrefixPtr has no > field or method outputString) > > I understand that golfing doesn’t have implicit type conversions, and that > PrefixPtr is not the same as *Prefix, so I guess what I’m asking is twofold: > > Why can’t receivers be a pointer type?
Because the language supports pointer methods, as in func (p *S) Set(...) { ... } That is a pointer method on the type S, and it can only be called on values of type *S or addressable values of type S. If a receiver type could be a type defined as a pointer type, it would be confusing whether methods declared on that type were pointer methods or value methods. And it would be confusing whether it were valid to declare a method on a pointer to that pointer type. We avoid those potential confusions by simply forbidding methods on types defined as pointer types. This does not cause any loss of functionality. > 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. Ian -- 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. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAOyqgcVDEve8U5H4SEqi0EES7h%2Btx-qH9tPfiPUuT70yrug3Dw%40mail.gmail.com.