proto3 不支持内建类型的非空判断即 hasXXX

时间:2020-12-02 18:44:34

proto3 移除了内建类型的非空判断方法

  • 即代码生成工具不会为 bool int 等类型生成has方法

有使用过proto2 或者其它rpc 框架的人都知道使用has 方法去判断消息里的值是否设置,

而在proto3 里只有自定义类型才能有这个方法了,

这个问题在github上引起激烈讨论, 以下是开发人员在github的解释

大致意思是从简易性和实践出发降低复杂度,停止支持为空的判断, 但是用户依旧有其它办法支持has,例如oneof和自定义类型

I brought up the syntax sugar proposal in #1606 (comment) to protobuf team meetings and after some discussions the decision is to not move forward with the proposal:

Rationale of removing field presence in proto3:
Field presence in proto2 has caused confusions and it complicates the semantics, e.g. one
has to distinguish between absence fields vs fields set to their default values; users usually
check presence before accessing the fields which is unnecessary. We believe in most cases,
field presence info is not needed.
Removing field presence makes Proto3 significantly easier to implement with open struct
representations, as in languages like Android Java (go/nano-proto), or Go. The easier
implementation in turn makes it better accessible to external implementer communities.
If such presence info is explicitly needed, there are several workarounds, e.g. wrappers, explicit
has_field boolean. Oneof can also be used if backward wire compatibility with proto2 optional
field is desired.
Introducing a new keyword or reusing an existing keyword to support field presence in proto3
will complicate protobuf semantics. We believe it will lead to confusion and misuse, which
defeats the purpose of removing field presence in proto3.

We may reconsider the proposal in the future when there are more data showing field presence are used more often than we expect in proto3, but at the moment we recommend users to design their proto3 protos without relying on field presence.