英文:
GO GRPC function stub definition issue
问题
我正在学习gRPC和Golang,对两者都是新手。在这个教程中有这个函数:
func (s *routeGuideServer) GetFeature(ctx context.Context, point *pb.Point) (*pb.Feature, error) {
...
}
我不明白这个函数桩中的(s *routeGuideServer)
部分是做什么的。
我已经学习了Go函数,根据我理解,(ctx context.Context, point *pb.Point)
是输入,(*pb.Feature, error)
是输出。
这个(s *routeGuideServer)
部分到底是什么意思?如果有解释的指引,我会很感激。
英文:
I'm studying gRPC and Golang and am new to both. In this tutorial there's this function:
func (s *routeGuideServer) GetFeature(ctx context.Context, point *pb.Point) (*pb.Feature, error) {
...
}
I don't understand what "(s *routeGuideServer)" part in this function stub doing.
I've learnt go functions and "(ctx context.Context, point *pb.Point)" is the input and "(*pb.Feature, error)" is the output as far as I understand.
What exactly is this "(s *routeGuideServer)" part? Any pointers towards an explanation would be appreciated.
答案1
得分: 3
这是函数接收器。
它有点像面向对象编程语言中的类,其中类型(*routeGuideServer)有一个函数(或者说方法)。
所以在这种情况下,routeGuideServer有一个GetFeature函数。你需要一个类型为routeGuideServer的值来调用该函数。
英文:
It's the function receiver.
It's kind of like a class in OOP languages, where the type (*routeGuideServer) has a function (or, method).
So in this case, the *routeGuideServer has a GetFeature function. You'll need a value of type *routeGuideServer to call that function.
答案2
得分: 1
在GRPC中,当你创建proto文件时,你声明的服务将成为服务器的接口。
你需要遵循这个接口,这意味着你需要一个包含这些方法的结构体。
因此,启动服务器的函数接受一个服务器接口作为参数,该接口要求实现你在服务中定义的所有RPC调用。为了遵循这个要求,需要一个包含所有方法的结构体。
如果结构体和方法不是语言的一部分,那么这个函数将需要逐个接受每个函数。
一个重要的好处是,当你初始化这个结构体时,它可以拥有字段,比如数据库连接,在每个方法中都可以使用。
英文:
In GRPC when you make your protofile, the services you declare becomes an interface for the server.
You need to adhere to this interface, which means you need a struct that have these methods.
So the function that starts the server takes in an interface for the server, that requires all the rpc calls you defined under services. So to adhere to this, a struct is needed with all the methods.
If structs and methods were not a part of the language, the function would need to take in each function individually.
One big benefit is that when you initialize the struct, it can have fields, such as a database connection, which in return is available in each method.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论