【问题标题】:No 'return' in Golang for method that return values对于返回值的方法,Golang 中没有“返回”
【发布时间】:2017-08-15 20:29:22
【问题描述】:

我正在看 Go 的视频教程。我看到有一个类型声明和方法必须返回该类型的指针。

type testType struct {
    value int
}

func (h *testType) testFunction(w http.ResponseWriter, r *http.Request) {
    // we have empty body
}

如你所见,函数体是空的,没有返回语句。

  • 为什么会编译?我不知道必须返回某些值的方法允许缺少“返回”指令。你能告诉我什么时候它们不是强制性的吗?
  • 在这种情况下会返回什么值?总是零?

【问题讨论】:

    标签: go


    【解决方案1】:

    这不是函数的返回类型,它是一个方法,称为接收者类型。

    请参阅 Spec: Function declarationsSpec: Method declarations

    返回类型在函数Signature的末尾,例如:

    func testFunction(w http.ResponseWriter, r *http.Request) *testType {
        return nil
    }
    

    这是一个函数,返回类型为*testType

    这个:

    func (h *testType) testFunction(w http.ResponseWriter, r *http.Request) {
        // we have empty body
    }
    

    是一个接收者类型为*testType的方法,没有返回类型。

    【讨论】:

      猜你喜欢
      • 2022-12-18
      • 1970-01-01
      • 2020-07-16
      • 1970-01-01
      • 1970-01-01
      • 2021-04-02
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      相关资源
      最近更新 更多