Groups keyboard shortcuts have been updated
Dismiss
See shortcuts

Constructing C++ protos using structs and initializer lists

26 views
Skip to first unread message

David Chen

unread,
May 5, 2025, 2:34:36 AMMay 5
to Protocol Buffers
Hi all,

In Go, protos can be constructed using struct literals. For instance:

p := pb.Person{
  Id:    1234,
  Name:  "John Doe",
  Email: "jd...@example.com",
  Phones: []*pb.Person_PhoneNumber{
    {Number: "555-4321", Type: pb.PhoneType_PHONE_TYPE_HOME},
  },
}

On the other hand, in C++, you have to instantiate the proto then use setter fields:

Person p;
person.set_id(1234);
person.set_name("John Doe");
person.set_email("jd...@example.com");
Person::PhoneNumber* phone_number = person.add_phones();
phone_number->set_number("555-4321");
phone_number->set_type(PhoneType::PHONE_TYPE_NONE);

It would be nice if the generated C++ code generated some structs, which could be used to construct protos using initializer lists, which IMO would be cleaner. Perhaps something like:

PersonSpec spec = {
    .id = 1234,
    .name = "John Doe",
    .email = "jd...@example.com",
    .phones = {
        {.number = "555-4321",
         .type = PhoneType::PHONE_TYPE_NONE},
    },
};
Person proto(spec);

Has the team considered something like this? I think it would make constructing protos in C++ look cleaner and clearer.

Best,
David
Reply all
Reply to author
Forward
0 new messages