Protocol Buffer use enum

Viewed 9100

Hello I'm working with protobuf but I have a problem.

I have some enum functions but in tow of these I have the same alias, when I try to compile the file for some language "go" the compiler return an error.

I copied the example in protobuf documentation to define the enum and still not working.

enum EnumAllowingAlias {
  option allow_alias = true;
  UNKNOWN = 0;
  STARTED = 1;
  RUNNING = 1;
}
enum EnumNotAllowingAlias {
  UNKNOWN = 0;
  STARTED = 1;
  // RUNNING = 1;  // Uncommenting this line will cause a compile error inside Google and a warning message outside.
}

This is the google documentation said if you need to use the same alias in some different enums you need to add the option "option allow_alias = true;" in the enum but after try to compile the .proto file the compiler response.

example.proto:13:5: "UNKNOWN" is already defined in "namespace".
example.proto:13:5: Note that enum values use C++ scoping rules, meaning that enum values are siblings of their type, not children of it.
Therefore, "UNKNOWN" must be unique within "kluso", not just within "EnumNotAllowingAlias".

example.proto:14:5: "STARTED" is already defined in "namespace".
example.proto:14:5: Note that enum values use C++ scoping rules, meaning that enum values are siblings of their type, not children of it.
Therefore, "STARTED" must be unique within "kluso", not just within "EnumNotAllowingAlias".

I don't know what's happen. Someone know what is the problem?

4 Answers

allow_alias allows you to have two different names for the same value.

However, it still doesn't allow you to use the same name twice!

In the example you took from the docs, they are just trying to demonstrate how you can use STARTED = 1 and RUNNING = 1 in the same enum type by setting allow_alias to be true. The two enums example they gave are not meant to be used in the same package.

But if you already have RUNNING in EnumAllowingAlias, you cannot use RUNNING again in EnumNotAllowingAlias if they are in the same package.

EnumAllowingAlias and EnumNotAllowingAlias can't be defined in the same proto file, they are just two examples for understanding the usage of allow_alias.

allow_alias only work in the same enum, as mahdt said, allow_alias allows you to have two different names for the same value in a enum, the EnumAllowingAlias is the example for this case:

enum EnumAllowingAlias {
  option allow_alias = true;
  UNKNOWN = 0;
  STARTED = 1;
  RUNNING = 1;
}

If allow_alias is not set to true, the the EnumNotAllowingAlias will get an error:

enum EnumNotAllowingAlias {
  UNKNOWN = 0;
  STARTED = 1;
  RUNNING = 1;  // Uncommenting this line will cause a compile error inside Google and a warning message outside.
}

Enum usage don't have this limit in Java, I think it is really confusing for most developers, so I raised a bug report: https://github.com/protocolbuffers/protobuf/issues/5425

Related