为什么Go语言接受这种方法定义语法?

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

why is this method definition syntax accepted in Go?

问题

代码部分的翻译如下:

  1. package main
  2. import "fmt"
  3. type unimplementedGreeterServer struct {
  4. }
  5. func (unimplementedGreeterServer) SayHello() string {
  6. return "hello"
  7. }
  8. func main() {
  9. s := &unimplementedGreeterServer{}
  10. ret := s.SayHello()
  11. fmt.Println(ret)
  12. }

结果部分的翻译如下:

  1. hello

问题部分的翻译如下:

为什么SayHello方法没有unimplementedGreeterServer指针或unimplementedGreeterServer接收器也能运行?

我认为正确的写法应该是:

  1. func (s unimplementedGreeterServer) SayHello2() string {
  2. return "hello"
  3. }
  4. func (s *unimplementedGreeterServer) SayHello3() string {
  5. return "hello"
  6. }

而不是:

  1. func (unimplementedGreeterServer) SayHello() string {
  2. return "hello"
  3. }
英文:

the code

  1. package main
  2. import "fmt"
  3. type unimplementedGreeterServer struct {
  4. }
  5. func (unimplementedGreeterServer) SayHello() string {
  6. return "hello"
  7. }
  8. func main() {
  9. s := &unimplementedGreeterServer{}
  10. ret := s.SayHello()
  11. fmt.Println(ret)
  12. }

the result

  1. hello

the question :
why the SayHello method has no unimplementedGreeterServer point or unimplementedGreeterServer receiver can run

I think the right will be

  1. func (s unimplementedGreeterServer) SayHello2() string {
  2. return "hello"
  3. }
  4. func (s *unimplementedGreeterServer) SayHello3() string {
  5. return "hello"
  6. }

not

  1. func (unimplementedGreeterServer) SayHello() string {
  2. return "hello"
  3. }

答案1

得分: 3

接收器本身是可选的。如果方法不使用接收器,可以省略它。下面的声明:

  1. func (unimplementedGreeterServer) SayHello() string {
  2. return "hello"
  3. }

只是定义了一个不使用接收器的unimplementedGreeterServer方法。它是为值接收器定义的,因此它适用于unimplementedGreeterServer*unimplementedGreeterServer

英文:

The receiver itself is optional. If the method does not use the receiver, you can omit it. The declaration:

  1. func (unimplementedGreeterServer) SayHello() string {
  2. return "hello"
  3. }

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.

huangapple
  • 本文由 发表于 2021年11月21日 11:05:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/70051506.html
匿名

发表评论

匿名网友

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

确定