1

I am learning about protobuf and gRPC in Go. Upon generating pb.go file with

protoc --go_out=plugins=grpc:chat chat.proto

for the file chat.proto

syntax = "proto3";
package chat;

message Message {
  string body = 1;
}

service ChatService {
  rpc SayHello(Message) returns (Message) {}
}

The generated chat.pb.go has these 2 interfaces:

type ChatServiceClient interface {
    SayHello(ctx context.Context, in *Message, opts ...grpc.CallOption) (*Message, error)
}
...
type ChatServiceServer interface {
    SayHello(context.Context, *Message) (*Message, error)
}

I am confused with the use of named parameters in ChatServiceClient interface. Is there any use of these parameters: ctx, in and opts. When should we have named vs unnamed parameters in such a case?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
subtleseeker
  • 4,415
  • 5
  • 29
  • 41

1 Answers1

4

Parameter names are optional, and in case of interfaces it may be provided purely for documentational purposes.

Spec: Interfaces:

InterfaceType      = "interface" "{" { ( MethodSpec | InterfaceTypeName ) ";" } "}" .
MethodSpec         = MethodName Signature .

Where the method Signature is:

Signature      = Parameters [ Result ] .
Result         = Parameters | Type .
Parameters     = "(" [ ParameterList [ "," ] ] ")" .
ParameterList  = ParameterDecl { "," ParameterDecl } .
ParameterDecl  = [ IdentifierList ] [ "..." ] Type .

As you can see, IdentifierList in ParameterDecl is in square brackets which means it is optional.

Think of an example like this:

type FileMover interface {
    MoveFile(dst, src string) error
}

It's "loud and clear". What if we omit the parameter names?

type FileMover interface {
    MoveFile(string, string) error
}

It's not obvious if the first parameter identifies the source or destination. Providing the dst and src names documents that, it makes thar clear.

When you implement an interface and you provide the implementation for a method, and if you want to refer to the parameters, you have to name them because you refer to them by their names, but if you don't want to refer to the parameters, even then they may be omitted.

See related question: Is unnamed arguments a thing in Go?

icza
  • 389,944
  • 63
  • 907
  • 827