简体   繁体   English

GO GRPC function 存根定义问题

[英]GO GRPC function stub definition issue

I'm studying gRPC and Golang and am new to both.我正在研究 gRPC 和 Golang,并且对两者都很陌生。 In this tutorial there's this function:教程中有这个 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.我不明白这个 function 存根中的“(s *routeGuideServer)”部分在做什么。

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.据我所知,我已经学习了 go 函数和“(ctx context.Context,point *pb.Point)”是输入,“(*pb.Feature,error)”是output。

What exactly is this "(s *routeGuideServer)" part?这个“(s *routeGuideServer)”部分到底是什么? Any pointers towards an explanation would be appreciated.任何指向解释的指针将不胜感激。

It's the function receiver.它是 function 接收器。

https://go.dev/tour/methods/4 https://go.dev/tour/methods/4

It's kind of like a class in OOP languages, where the type (*routeGuideServer) has a function (or, method).它有点像 OOP 语言中的 class,其中类型 (*routeGuideServer) 具有 function (或方法)。

So in this case, the *routeGuideServer has a GetFeature function.所以在这种情况下,*routeGuideServer 有一个 GetFeature function。 You'll need a value of type *routeGuideServer to call that function.您需要一个 *routeGuideServer 类型的值来调用 function。

In GRPC when you make your protofile, the services you declare becomes an interface for the server.在 GRPC 中,当您制作 protofile 时,您声明的服务将成为服务器的接口。

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.因此,启动服务器的 function 接受服务器的接口,这需要您在服务下定义的所有 rpc 调用。 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.如果结构和方法不是语言的一部分,则 function 将需要单独接收每个 function。

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.一个很大的好处是,当您初始化结构时,它可以包含字段,例如数据库连接,作为回报,这些字段在每个方法中都可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM