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

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

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.

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:

确定