That's interesting, I didn't even realize that was valid syntax :). I've always prefered underscore to make it explicit that I'm not using the receiver:
func (_ foo) method() {
...
}
@willnorris I actually used to also prefer the (_ foo) syntax, for the same reason you said. It's a more explicit way of saying that "I'm literally not using the receiver at all."
However, I later found evidence that it's more idiomatic to skip the _ altogether, so I simplified my style to follow suit. I should dig it up and add it to the references section. :)
In my limited exposure, I haven't seen this usage. An example (or pointer to actual usage) would be helpful.
@tedyoung This is one of the few suggestions that I came up with on my own, rather than from spotting an existing pattern. The motivation for doing this is as described:
It's more readable because it's clear that fields or methods of
fooare not used inmethod.
So the reason for doing this is to help increase code readability, it's not for consistency with existing code. I'm sure this is used in some codebases but not others. I don't have links right now.
When would you do this as opposed to not attaching it to the receiver at all?
@thomshutt Both are valid, it depends on the situation.
Changing a method to a function is a bigger change that could break some other code, whereas not including the receiver (when it's unused) is a smaller change that would never affect the behavior.
If the receiver is completely unused, that's definitely a sign that maybe it's a good idea to turn it into a function rather than method. But sometimes you might want to keep it a method for various reasons. Perhaps to continue to implement an interface.
I have to say "_" is a great choice because in other contexts it is the Go way of saying "I have to have this thing, but I don't need this thing". One look at a "_" in Go and you know the deal.
(double post)
Is there a tool that finds all unused method receivers in a file/package?
@ilius, @dmitshur, one of the +50 rules of revive detects unused receivers.
Do this:
Don't do this:
If
fis unused. It's more readable because it's clear that fields or methods offooare not used inmethod.