Bre*_*sta 5 go protocol-buffers
我有类似的设置,如下所示,如何XYZ使用“github.com/golang/protobuf/proto”从枚举访问我的扩展值?
extend google.protobuf.EnumValueOptions {
Details meta = 50001;
}
message Details {
string description = 1;
}
enum MyEnum {
MY_ENUM_UNSPECIFIED = 0;
XYZ = 1 [deprecated=true, (meta) = {description: "lorem ipsum"}];
}
Run Code Online (Sandbox Code Playgroud)
我知道proto.GetExtension(proto.Message, proto.ExtensionDesc),但是我无法弄清楚它如何用于枚举......
当前最佳答案中使用的一些方法现已弃用,并且有点冗长。
这是我得到它的方法:
// pd is the module of your complied protobuf files
fd := pd.File_name_of_your_proto_file_proto
enumDesc := fd.Enums().ByName("MyEnum")
if enumDesc == nil {
panic()
}
enumValDesc := enumDesc.Values().ByName("XYZ")
if enumValDesc == nil {
panic()
}
ext := proto.GetExtension(enumValDesc.Options(), pd.E_Meta)
if enumValDesc == nil {
panic()
}
meta := ext.(*Details)
Run Code Online (Sandbox Code Playgroud)
让我知道是否有更好的方法。
有点晚了,但我刚刚遇到了同样的事情;你可以这样做:
fd, _ := descriptor.ForMessage(&pb.Details{})
for _, e := range fd.EnumType {
if e.GetName() == "MyEnum" {
for _, v := range e.Value {
ext, err := proto.GetExtension(v.Options, pb.E_Meta)
if err == nil {
details := ext.(*pb.Details)
// do stuff with details
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
可能有一种更直接的方法来获取枚举描述符,尽管我在一番争论后还没有成功。
| 归档时间: |
|
| 查看次数: |
4248 次 |
| 最近记录: |