Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protocol Buffers 3: Enums as keys in a map

Enums are not allowed to be used as keys in map. PaxType here is an enum and not allowed to be used as key.

enum PaxType {
    ADULT = 0 ;
    CHILD = 1 ;
    INFANT = 2 ;
}

message FlightData {
    map<PaxType, FareType> fareType = 1;
}
like image 623
Vivek Sinha Avatar asked Dec 14 '16 08:12

Vivek Sinha


People also ask

Can I use enum as map key?

In HashMap, we can use Enum as well as any other object as a key.

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.

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.

What is oneof 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.


1 Answers

This is disallowed because it doesn't play well with proto3 open enum semantics. For example, in Java, if you have a Map, the key can only be one of the defined values. If you happen to receive an enum key value from a remote client/server that's not in the defined value set, it can't be put in the Map. This limitation forces us to either drop map entries with unknown enum keys (which is against proto3 open enum semantics), or disallow enum as map keys all together.

for reference: https://groups.google.com/forum/#!topic/protobuf/ikeldBe60eI

like image 115
Vivek Sinha Avatar answered Nov 10 '22 00:11

Vivek Sinha