protocol-buffersgrpcrpc

Is there a way to use a Message type as a type in another Message?


I'd like to assign a "message" type to Message so payload can be either Sms or Email. This is not valid type as the error says message not defined in reference to the "message" type I'm assigning to payload.

Is there some way I can make the payload be a generic enough type that it can be either Sms or Email?

syntax = "proto3";


message Sms {
    ...
}

message Email {
    ...
}


message Message {
    // Can be any form of communication.
    message payload = 1;  // I want to make this any kind of message. 
}

Alternatively, I was going to add both types able to be assignable to the Message.

syntax = "proto3";


message Sms {
    ...
}

message Email {
    ...
}


message Message {
    // Can be any form of communication.
    optional Sms sms = 1;
    optional Email email = 2;
}

Solution

  • message Message {
      oneof payload {
        Sms sms = 1;
        Email email = 2;
      }
    }