Here is a protobuf message definition:
message People {
enum PeopleName {
Alice = 100;
Bob = 101;
Cathy = 102;
}
optional PeopleName name = 1;
}
I would like to populate the name field based on some strings I created. E.g. in golang:
str := "Cathy"
How can I populate the "name" in the protobuf message?
enum is one of the composite datatypes of Protobuf. It translates to an enum in the languages that we use, for example, Java.
Inheritance is not supported in protocol buffers.
Protocol Buffer (Protobuf) provides two simpler options for dealing with values that might be of more than one type. The Any type can represent any known Protobuf message type. And you can use the oneof keyword to specify that only one of a range of fields can be set in any message.
Proto3 is the latest version of Protocol Buffers and includes the following changes from proto2: Field presence, also known as hasField , is removed by default for primitive fields. An unset primitive field has a language-defined default value.
The Go protobuf generator emits a map of enum names to values (and vice versa). You can use this map to translate your string to enum value:
str := "Cathy"
value, ok := People_PeopleName_value[str]
if !ok {
panic("invalid enum value")
}
var people People
people.Name = People_PeopleName(value).Enum()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With