简体   繁体   English

可以protobuffer自动填充新创建对象的默认值

[英]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. 因此, requireddefault的组合是没有意义的。

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.

相关问题 如何将当前进程分配给新创建的作业对象? - How can I assign the current process to a newly created job object? 如果我们用一个构造函数转换一个值,是否还需要复制构造函数来复制新创建的临时 object? - If we convert a value with one constructor, will there also be copy constructor needed to copy the newly created temp object? 如何将新创建的 object 添加到数组中 - How to add newly created object into array cout 新创建的对象抛出运行时错误 - cout newly created object throws runtime error 新构造的对象作为默认模板函数参数 - Newly constructed object as default template function argument 从新创建的对象指针正确调用方法 - Correctly Call a Method From Newly Created Object Pointer 将新创建的对象传递给函数时是否可以避免复制构造函数? - Is it possible to avoid the copy constructor when passing newly created object to a function? 默认 function 可以返回自动吗? - Can a default function return auto? C ++函数,我可以为对象提供什么默认值? - C++ function, what default value can I give for an object? 如果从 lambda 表达式生成的类没有默认构造函数,那么如何创建生成的 class 类型的 object - If classes generated from lambda expression do not have default ctor then how can an object of that generated class type be created
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM