Search code examples
c++protocol-buffers

Copy protobuf field to another protobuf in C++


We have the following protobuf definition

message SubMessage {
  optional string var_1 = 1;

  repeated string var_2 = 2;
}

message MainMessage {
  repeated Foo1 foo_1 = 1;

  repeated Foo2 foo_2 = 2;

  optional SubMessage foo_3 = 6;
}

When trying to merge this subproto as part of the main proto

 proto::MainMessage main_message_proto;
 proto::SubMessage submessage_proto;

 ...

 main_message_proto.MergeFrom(submessage_proto);

The following error occurs:

Tried to merge messages of different types

What's the correct function to merge the information of the submessage as a field of the main message?


Solution

  • MergeFrom merges two messages of the same type. For example, if you had one MainMessage with its foo_1 field set and another with its foo_2 field set, you could merge them together and the result would be a message with both the foo_1 and foo_2 fields set.

    But that's not what you have here. You have a MainMessage and want to merge its SubMessage field with another SubMessage. To do that you need to call MergeMessage on foo_3:

    main_message_proto.mutable_foo_3()->MergeFrom(submessage_proto);
    

    If foo_3 is currently empty, then there's no need to use MergeFrom. Simple assignment will do in that case:

    *main_message_proto.mutable_foo_3() = submessage_proto;