18910140161

protobuf里如何定义字符串常量枚举?

顺晟科技

2022-09-15 20:04:27

85

疑问是:如何定义一个pb文件,枚举类型TYPES的每种枚举都能同时对应一个字符串常量?

如下proto协议:

enum TYPES {
    TYPE0 = 0;
    TYPE1 = 1;
    TYPE2 = 2;
}

XXX_enum {  //也不知道该用什么类型表示
    TYPES::TYPE0 = "type0的说明";
    TYPES::TYPE1 = "type1的说明";
    TYPES::TYPE2 = "type2的说明";
}

protobuf 在大部分语言里已经自带了这个信息。

c++:

const string& Foo_Name(int value): Returns the name for given numeric value. Returns an empty string if no such value exists. If multiple values have this number, the first one defined is returned. In the above example, Foo_Name(5) would return "VALUE_B".

go:

The protobuf compiler also generates a map from integer values to the string names and a map from the names to the values:

var Foo_name = map[int32]string{
       0: "DEFAULT_BAR",
       1: "BAR_BELLS",
       2: "BAR_B_CUE",
}
var Foo_value = map[string]int32{
        "DEFAULT_BAR": 0,
        "BAR_BELLS":   1,
        "BAR_B_CUE":   2,
}

上面 Foo 是 enum 的名字。

其它的自己去看文档吧

相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航