douba4824 2016-03-22 11:15
浏览 56

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

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?

  • 写回答

2条回答 默认 最新

  • doulu4203 2016-03-22 11:30
    关注

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

    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向