Golang中没有用于返回值的’return’关键字的方法。

huangapple go评论104阅读模式
英文:

No 'return' in Golang for method that return values

问题

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

type testType struct {
    value int
}

func (h *testType) testFunction(w http.ResponseWriter, r *http.Request) {
    // 这里是空的函数体
}

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

  • 为什么它能编译通过?我不知道对于必须返回某个值的方法,缺少'return'指令是被允许的。你能告诉我什么时候它们不是必需的吗?
  • 在这种情况下会返回什么值?总是返回nil吗?
英文:

I'm looking to the video tutorial of Go. I see there a type declaration and method that have to return a pointer of that type.

type testType struct {
    value int
}

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

As you see, function body is empty, there is no return statement.

  • Why does it compile? I did not know that missing 'return' directives are permitted for methods that have to return some value. Could you tell me when they are not mandatory?
  • What value will be returned in this case? Always nil?

答案1

得分: 10

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

请参阅规范:函数声明规范:方法声明

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

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

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

而这个:

func (h *testType) testFunction(w http.ResponseWriter, r *http.Request) {
    // 我们没有具体的函数体
}

是一个具有接收器类型*testType且没有返回类型的方法。

英文:

That is not the return type of the function, it's a method and that is called the receiver type.

See Spec: Function declarations and Spec: Method declarations.

The return type is at the end of the function Signature, for example:

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

This is a function, having a return type of *testType.

This:

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

Is a method with receiver type *testType, and no return types.

huangapple
  • 本文由 发表于 2017年3月23日 18:30:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/42973442.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定