Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the enum value out from protobuf messages

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?

like image 394
drdot Avatar asked May 04 '17 17:05

drdot


People also ask

What is enum in Protobuf?

enum is one of the composite datatypes of Protobuf. It translates to an enum in the languages that we use, for example, Java.

Does Protobuf have inheritance?

Inheritance is not supported in protocol buffers.

What is oneof in Protobuf?

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.

What is the difference between proto2 and Proto3?

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.


1 Answers

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()
like image 112
Tim Cooper Avatar answered Oct 19 '22 01:10

Tim Cooper