Let's say I have a struct
type Rectangle struct {
length, width int
}
and I want to add a method to it:
func (r Rectangle) Area() int {
return r.length * r.width
}
Why must I give it a variable name here r
?
Let's say I have a struct
type Rectangle struct {
length, width int
}
and I want to add a method to it:
func (r Rectangle) Area() int {
return r.length * r.width
}
Why must I give it a variable name here r
?
Because there is no implicit identifier denoting the actual receiver value (like this
in Java), and if you want to refer to the fields or methods of the receiver value (Rectangle
value), you need an identifier that you can use.
Note that the spec does not require you to name the receiver value, e.g. the following using the blank identifier is a valid syntax:
func (_ Rectangle) Foo() string {
return "foo"
}
Or even this: omitting the receiver name (the parameter name):
func (Rectangle) Foo() string {
return "foo"
}
Relevant section from the spec: Method declarations:
MethodDecl = "func" Receiver MethodName ( Function | Signature ) . Receiver = Parameters .
Where Parameters is:
Parameters = "(" [ ParameterList [ "," ] ] ")" . ParameterList = ParameterDecl { "," ParameterDecl } . ParameterDecl = [ IdentifierList ] [ "..." ] Type .
As you can see in the last line, the IdentifierList
is optional (but Type
is required).