为Golang中的结构添加方法时,为什么我们必须声明一个变量名? [英] Why must we declare a variable name when adding a method to a struct in Golang?

查看:87
本文介绍了为Golang中的结构添加方法时,为什么我们必须声明一个变量名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个struct

 类型Rectangle struct {
length,width int
}

并且我想添加一个方法:

  func(r Rectangle)Area()int {
return r.length * r.width
}

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

$ b $因为不存在表示实际接收者值的隐式标识符(例如Java中的 this ),并且如果你想引用接收者值的字段或方法( Rectangle value),你需要一个你可以使用的标识符。 p>

请注意,该规范并不要求您命名接收器值,例如以下使用空白标识符是一种有效的语法:

 func(_ Rectangle)Foo()string {
returnfoo
}

甚至可以这样做:省略接收者名称(参数名称):

$ $ p $ func (Rectangle)Foo()string {
returnfoo
}

规范中的相关部分:方法声明


  MethodDecl =funcReceiver MethodName(Function | Signature)。 
Receiver =参数。


其中参数为:


 参数=([ParameterList [,]])。 
ParameterList = ParameterDecl {,ParameterDecl}。
ParameterDecl = [标识符列表] [...]类型。


正如您在最后一行所看到的那样, IdentifierList 是可选的(但需要 Type )。


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

这篇关于为Golang中的结构添加方法时,为什么我们必须声明一个变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆