You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
optional、required和默认值
proto2 中有optional、required和默认值这些东西,proto3中去掉了这些,默认就是optional的。
默认值的处理
proto2 的默认值如何处理?比如这样一个message:
如何与struct_pb 的结构体对应起来呢?按照普通结构体的默认值去处理。
序列化的时候需要先通过get_default获取初始化的静态point对象,序列化具体的point字段时需要和静态point对象的字段做比较,如果二者字段值相等,则该字段忽略掉不要序列化。
对于proto3 来说由于没有默认值的概念,只要值是0或者空值时就不去序列化。
proto2 中的optional 数字和字符串类型对应的C++ 结构体就是普通的数字和字符串类型,不需要加std::optional,proto3中也是如此。
proto2 中的optional message,optional repeated, optional map 类型对应到C++的结构体才是std::optional。proto3 中的上述类型都应该默认加std::optional。
因此,从概念上来说proto的optional是部分对应std::optional的,不是完全对应。
optional的处理
optional message类型如果设置了就序列化如果没设置就不序列化。
required 的处理
proto2 中的required 现在在struct_pb中还没有对应的类型,需要增加一个
required_t<T>
的类型来表示required的字段,对于required 字段,无论是否设置过都应该序列化。Beta Was this translation helpful? Give feedback.
All reactions