【问题标题】:Function declaration syntax in GoGo 中的函数声明语法
【发布时间】:2015-07-23 18:46:10
【问题描述】:

以下函数声明中的 (c App) 是什么?

func (c App) SaveSettings(setting string) revel.Result {
--------------------------------------------------------------------------------------
func                                                      Keyword to define a function
     (c App)                                              ????
             SaveSettings                                 Function name
                         (setting string)                 Function arguments
                                          revel.Result    Return type

【问题讨论】:

  • 我建议不要问这样的问题,而是略读简短且容易找到的Go Language Specification。国际海事组织(IMO),问题和答案只不过是反刍现成和更权威来源的部分内容是没有用的。
  • 1) 我不会说该文档很短。 2)我已经看过那个文档了,但是我看的是函数声明,而不是方法声明,因为我对 Go 一无所知:golang.org/ref/spec#Function_declarations 3)实际上一切都可以在更权威的来源中找到。我认为这个问题可能对未来学习 Go 的人有用,并且非常适合 Stack Overflow。
  • @Ivan,同意,我也在看 Function_declarations!而且文档不短。

标签: function syntax go


【解决方案1】:

(c App) 给出了接收器的名称和类型,Go 相当于 C++ 或 JavaScript 的 this 或 Python 的 self。 c 是这里的接收者的名字,因为in Go it's conventional to use a short, context-sensitive name instead of something generic like this。见http://golang.org/ref/spec#Method_declarations--

方法是带有接收器的函数。接收者是通过方法名称前面的额外参数部分指定的。

及其示例:

func (p *Point) Length() float64 {
    return math.Sqrt(p.x * p.x + p.y * p.y)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多