Un-named receivers and parameters in methods

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.

2 Likes

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.

2 Likes

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

2 Likes

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

2 Likes

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

2 Likes

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.

2 Likes

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

3 Likes

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

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.