使用 protobuf 枚举值作为字段编号

问题描述 投票:0回答:2

我想知道是否可以使用 Google Protocol Buffers 的枚举常量作为其他消息的字段号,例如

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

message Message {
  required string foo = FOO;
}

此代码不起作用,因为

FOO
的类型是
enum Code
并且只能使用数字作为字段编号。

我正在尝试构建像这样的 animal example 的多态消息定义,它将

Cat = 1;
enum Type
中的
required Cat animal = 100;
定义为唯一的分机号。

我觉得这样做会很好

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

,这样我就可以保证扩展字段编号的唯一性,而无需引入另一个幻数。

所以问题:是否可以在协议缓冲区语言中引用枚举的整数值?

enums protocol-buffers
2个回答
3
投票

不,没有办法做到这一点。对不起。

顺便说一句,相同枚举类型的两个枚举实际上可以具有相同的数值,因此在枚举中定义这些值实际上并不能确保唯一性。


0
投票

通过Protobuf oneof的介绍,现在这是可以的了,如下

message Animal
{    
    oneof Type
    {
        Cat cat = 101;
        Dog dog = 102;
    }
}

message Cat
{    
    // These fields can use the full number range.
    optional bool declawed = 1;
}

message Dog
{    
    // These fields can use the full number range.
    optional uint32 bones_buried = 1;
}
© www.soinside.com 2019 - 2024. All rights reserved.