26
votes

I'm trying to use Google protobuf and i 'm having the next descriptions:

message.proto file:

message Request {
   required int32 id = 1;
   optional string value = 2;
}

service.proto file:

import "message.proto";

service Service {
    rpc request (Request) returns (bool);
}

I'm trying to generate c++ sources and getting an error:

$ protoc service.proto --cpp_out=/tmp/proto/build

service.proto:4:40: Expected message type.

Do i have to return user-defined types only? Are primitive (like bool or string) supported? Can i use primitive types as service method argument (instead of Request in my example)?

3
How about message Bool { bool status = 1; }Ben Affleck

3 Answers

37
votes

No, you cannot use a primitive type as either the request or response. You must use a message type.

This is important because a message type can be extended later, in case you decide you want to add a new parameter or return some additional data.

7
votes

If you want to return a primitive type, wrap it in a message and return it:

message Name {
  string name = 1;
}

In case you don't want to return anything, void I mean, you can just create an empty message:

message Void {} 

message Name {
  string name = 1;
}

..
service MyService{
  rpc MyFunc(Name) returns (Void);
}
3
votes

You can return scalar datatypes like bool, int, etc by making use of wrappers.proto

service.proto file:

import "message.proto";
import "google/protobuf/wrappers.proto";

service Service {
    rpc request (Request) returns (.google.protobuf.BoolValue); 
}