英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论