Un-named receivers and parameters in methods


(Sean Manierre) #1

I’m making a program that parses go files to extract types and methods and such from the files. I’ve been using it on the standard library at first since I figured that should be a good sample set. While looking through the files I saw some methods that were not being parsed correctly in the net/http package. These are the methods:

type noBody struct{}

func (noBody) Read([]byte) (int, error)         { return 0, io.EOF }
func (noBody) Close() error                     { return nil }
func (noBody) WriteTo(io.Writer) (int64, error) { return 0, nil }

While all three methods are an issue the biggest one is WriteTo. I’m used to the syntax:
func (n noBody) WriteTo(w io.Writer) (int64, error) {return 0, nil }

I’ve been able to get the nameless receiver parsed correctly but the nameless parameter is still giving me a bit of trouble due to the similarities of the syntax func Test(a, b, c string){}.

My question is, is that syntax (nameless receivers and parameters) common in a lot of code, or just in certain cases in the standard library. If it’s gonna be used only in cases like this, where no one will really be using the methods outside of the standard libraries, I may just ignore them.


(Christophe Meessen) #2

Nameless receiver is when you don’t use the receiver in the code. Otherwise, the compiler complains that a variable is defined and not used. This helps to find typing errors in the code.

Same for arguments. The nameless argument is when you don’t use the argument. You don’t specify a parameter name, otherwise the compiler will complain that a variable is defined and not used.

You should not ignore it. You will have to use it where it will make sense. So better understand when this syntax is used.


(Sean Manierre) #3

Ok that makes sense. Guess i’ll be spending some time trying to figure out how to recognize it when parsing files.


(Christophe Meessen) #4

There is indeed an ambiguity with func Test(a, b, c string){}. a and b could be types, or parameters of type string.


(Sean Manierre) #5

I think i’m gonna do something along the lines of “if there is no explicit type on the parameter, and it has a ‘.’, then it will be parsed as a nameless parameter. If there is no ‘.’, but there is a type within the package with the same name, it will be parsed as a nameless parameter. If neither of those are true then just assume it’s the same as the following parameter type.”


(Jakob Borg) #6

I suggest reading the spec and following it. :slight_smile: Specifically in this case: https://golang.org/ref/spec#Function_types

Either all parameters are named or none are, same
as for the return values. There is no ambiguity.


(Sean Manierre) #7

Well would you look at that. That makes it much easier. :+1:


(Christophe Meessen) #8

Thank you, for clarifying this. I also forgot about the possibility to use _ as name of an unused parameter.