Golang中没有'return'返回值的方法

Vit*_*lii 1 go

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

type testType struct {
    value int
}

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

如您所见,函数体是空的,没有return语句.

  • 为什么编译?我不知道对于必须返回某些值的方法,允许缺少'return'指令.你能告诉我什么时候他们不是强制性的吗?
  • 在这种情况下将返回什么价值?总是零?

icz*_*cza 7

这不是函数的返回类型,它是一种方法,称为接收器类型.

请参见规范:函数声明规范:方法声明.

返回类型位于函数签名的末尾,例如:

func testFunction(w http.ResponseWriter, r *http.Request) *testType {
    return nil
}
Run Code Online (Sandbox Code Playgroud)

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

这个:

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

是一个接收器类型的方法*testType,没有返回类型.