为什么在 Golang 中向结构体添加方法时必须声明变量名?

假设我有一个结构


type Rectangle struct {

    length, width int

}

我想给它添加一个方法:


func (r Rectangle) Area() int {

    return r.length * r.width

}

为什么我必须在这里给它一个变量名r?


郎朗坤
浏览 172回答 2
2回答

慕容708150

因为没有隐式标识符来表示实际的接收者值(就像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必需的)。

ABOUTYOU

结构方法类似于类方法。变量“r”是对该方法所应用到的结构/类实例/对象的引用。如果没有该引用,您将无法访问该结构/对象中包含的任何内容。例如,我smallRectangle使用您的结构创建:var smallRectangle = Rectangle{5,3}现在我想使用 Rectangle 方法计算面积 Areaarea := smallRectangle.Area()让我们看看函数内部发生了什么。r从方法声明变成的副本,smallRectangle因为那是调用它的结构对象。func (smallRectangle Rectangle) Area() int {    return smallRectangle.length * smallRectangle.width}正如 Icza 所指出的,没有像selforthis这样的隐式标识符,因此该方法访问结构值的唯一方法是通过 identifier r。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go