如何在协议缓冲区中设计未来的附加枚举值? [英] How to design for a future additional enum value in protocol buffers?

查看:43
本文介绍了如何在协议缓冲区中设计未来的附加枚举值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

协议缓冲区的一个吸引人的特性是它允许您扩展消息定义而不会破坏使用旧定义的代码.对于枚举根据文档:

One of the attractive features of protocol buffers is that it allows you extend the message definitions without breaking code that uses the older definition. In the case of an enum according to the documentation:

枚举类型的字段只能有一组指定的常量作为其值(如果您尝试提供不同的值,解析器会将其视为未知字段)

a field with an enum type can only have one of a specified set of constants as its value (if you try to provide a different value, the parser will treat it like an unknown field)

因此,如果您扩展枚举并使用新值,那么旧代码中具有该类型的字段将是未定义的或具有其默认值(如果有).

therefore if you extend the enum and use the new value then a field with that type in old code will be undefined or have its default value, if there is one.

知道将来枚举可能会添加额外的值,有什么好的策略可以解决这个问题?

What is a good strategy to deal with this, knowing that in future the enum may have additional values added?

想到的一种方法是定义枚举的未定义"成员并将其设为默认值,然后旧代码将知道它已发送了无法解释的内容.这是否明智,有没有更好的方法来处理这种情况?

One way that comes to mind is to define an "undefined" member of the enum and make that the default, then old code will know it has been sent something that it can't interpret. Is that sensible, are there better ways to deal with this situation?

推荐答案

是的,最好的方法是使枚举中的第一个值类似于 UNKNOWN = 0.然后旧程序读取带有他们无法识别的枚举值的 protobuf 会将其视为 UNKNOWN 并希望他们能够合理地处理它,例如跳过该元素.

Yes, the best approach is to make the first value in the enum something like UNKNOWN = 0. Then old programs reading a protobuf with an enum value they don't recognize will see it as UNKNOWN and hopefully they can handle that reasonably, eg by skipping that element.

如果您想这样做,您还需要将枚举设为 optional 而不是 required.

If you want to do this you'll also want to make the enum be optional not required.

required 通常意味着我宁愿程序中止而不是处理它不理解的东西."

required, generally, means "I'd rather the program just abort than handle something it doesn't understand."

请注意,它必须是原始源代码中声明的第一个值 - 只是零值并不能使其成为默认值.

Note that it must be the first value declared in the proto source - just being the zero value doesn't make it the default.

这篇关于如何在协议缓冲区中设计未来的附加枚举值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆