Search code examples
enumsprotocol-buffers

Using protobuf enum value as a field number


I'm wondering if it is possible to use Google Protocol Buffers' enum constants as a field number of other messages, like

enum Code {
  FOO = 100;
  BAR = 101;
}

message Message {
  required string foo = FOO;
}

This code doesn't work because FOO's type is enum Code and only a number can be used as a field number.

I am trying to build polymorphic message definitions like this animal example, that defines Cat = 1; in enum Type and required Cat animal = 100; as a unique extension number.

I thought it'd be nice to do

message Message {
  required string foo = FOO.value;
}

, so that I can ensure the uniqueness of the extension field number without introducing another magic number.

So the question: is it possible to refer an enum's integer value in the protocol buffer language?


Solution

  • No, there is no way to do this. Sorry.

    BTW, two enumerants of the same enum type can actually have the same numeric value, so defining these values in an enum does not actually ensure uniqueness.