[英]can protobuffer auto fill default value for newly created object
I have a problem using google protobuf, I want to create an object with default attribute value: 我在使用Google protobuf时遇到问题,我想创建一个具有默认属性值的对象:
message Obj {
required string id = 1[default=123];
}
When serializing the above object: 序列化以上对象时:
string s;
Obj obj;
obj.SerializeToString(&s);
it complains: can't serialize becault it's missing required field id 它抱怨:无法序列化错误,缺少必填字段ID
The doc says the "default" value is used for parsing obj from string, not for serialize to string. 文档说“默认”值用于从字符串解析obj,而不是序列化为字符串。
Is it possible to create object with default value? 是否可以使用默认值创建对象?
No, you can't set the default value for the in-memory objects. 不可以,您不能为内存中对象设置默认值。
Defaults are only applied at deserialization time. 默认值仅在反序列化时应用。
required
makes the reader error if the field is missing. 如果缺少该字段,则
required
会导致读取器错误。 So the combination of required
and default
is pointless. 因此,
required
和default
的组合是没有意义的。
If you want to set an in memory default, make a factory function and use that. 如果要设置内存默认值,请使用工厂功能。
You can't serialize the default value, but you can make it an optional field. 您无法序列化默认值,但可以将其设为可选字段。 That way, When you deserialize the stream, you'll get an object where the field is missing and trying to get the value will give you the default value.
这样,当反序列化流时,您将得到一个缺少字段的对象,尝试获取该值将为您提供默认值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.