英文:
why is this method definition syntax accepted in Go?
问题
代码部分的翻译如下:
package main
import "fmt"
type unimplementedGreeterServer struct {
}
func (unimplementedGreeterServer) SayHello() string {
return "hello"
}
func main() {
s := &unimplementedGreeterServer{}
ret := s.SayHello()
fmt.Println(ret)
}
结果部分的翻译如下:
hello
问题部分的翻译如下:
为什么SayHello方法没有unimplementedGreeterServer指针或unimplementedGreeterServer接收器也能运行?
我认为正确的写法应该是:
func (s unimplementedGreeterServer) SayHello2() string {
return "hello"
}
func (s *unimplementedGreeterServer) SayHello3() string {
return "hello"
}
而不是:
func (unimplementedGreeterServer) SayHello() string {
return "hello"
}
英文:
the code
package main
import "fmt"
type unimplementedGreeterServer struct {
}
func (unimplementedGreeterServer) SayHello() string {
return "hello"
}
func main() {
s := &unimplementedGreeterServer{}
ret := s.SayHello()
fmt.Println(ret)
}
the result
hello
the question :
why the SayHello method has no unimplementedGreeterServer point or unimplementedGreeterServer receiver can run
I think the right will be
func (s unimplementedGreeterServer) SayHello2() string {
return "hello"
}
func (s *unimplementedGreeterServer) SayHello3() string {
return "hello"
}
not
func (unimplementedGreeterServer) SayHello() string {
return "hello"
}
答案1
得分: 3
接收器本身是可选的。如果方法不使用接收器,可以省略它。下面的声明:
func (unimplementedGreeterServer) SayHello() string {
return "hello"
}
只是定义了一个不使用接收器的unimplementedGreeterServer
方法。它是为值接收器定义的,因此它适用于unimplementedGreeterServer
和*unimplementedGreeterServer
。
英文:
The receiver itself is optional. If the method does not use the receiver, you can omit it. The declaration:
func (unimplementedGreeterServer) SayHello() string {
return "hello"
}
simply defines a method for unimplementedGreeterServer
that does not use the receiver. It is defined for a value receiver, so it is defined for unimplementedGreeterServer
and *unimplementedGreeterServer
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论