2 回答
TA贡献1831条经验 获得超4个赞
因为没有隐式标识符来表示实际的接收者值(就像this在 Java 中一样),如果你想引用接收者值 ( Rectanglevalue)的字段或方法,你需要一个可以使用的标识符。
请注意,规范不要求您命名接收器值,例如以下使用空白标识符的语法是有效的:
func (_ Rectangle) Foo() string {
return "foo"
}
甚至这样:省略接收者名称(参数名称):
func (Rectangle) Foo() string {
return "foo"
}
规范中的相关部分:方法声明:
MethodDecl = "func" Receiver MethodName ( Function | Signature ) .
Receiver = Parameters .
其中参数是:
Parameters = "(" [ ParameterList [ "," ] ] ")" .
ParameterList = ParameterDecl { "," ParameterDecl } .
ParameterDecl = [ IdentifierList ] [ "..." ] Type .
正如您在最后一行中看到的,IdentifierList是可选的(但Type必需的)。
TA贡献1812条经验 获得超5个赞
结构方法类似于类方法。变量“r”是对该方法所应用到的结构/类实例/对象的引用。如果没有该引用,您将无法访问该结构/对象中包含的任何内容。
例如,我smallRectangle使用您的结构创建:
var smallRectangle = Rectangle{5,3}
现在我想使用 Rectangle 方法计算面积 Area
area := smallRectangle.Area()
让我们看看函数内部发生了什么。r从方法声明变成的副本,smallRectangle因为那是调用它的结构对象。
func (smallRectangle Rectangle) Area() int {
return smallRectangle.length * smallRectangle.width
}
正如 Icza 所指出的,没有像selforthis这样的隐式标识符,因此该方法访问结构值的唯一方法是通过 identifier r。
- 2 回答
- 0 关注
- 171 浏览
添加回答
举报
