gpt4 book ai didi

c++ - protobuf 必填字段和默认值

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:35:33 28 4
gpt4 key购买 nike

我是 protobuf 的新手,我已经开始考虑以下简单的例子

message Entry {
required int32 id = 1;
}

由c++代码使用

#include <iostream>
#include "example.pb.h"
int main() {
std::string mySerialized;
{
Entry myEntry;
std::cout << "Serialization succesfull "
<< myEntry.SerializeToString(&mySerialized) << std::endl;
std::cout << mySerialized.size() << std::endl;
}
Entry myEntry;
std::cout << "Deserialization successfull "
<< myEntry.ParseFromString(mySerialized) << std::endl;
}

即使需要“id”字段,由于没有设置,序列化缓冲区的大小为0(??)。

当我反序列化消息时发生错误:

[libprotobuf ERROR google/protobuf/message_lite.cc:123] Can't parse message of type "Entry" because it is missing required fields: id

这是正常行为吗?

弗朗切斯科

ps- 如果我用值 0 初始化“id”,行为是不同的

pps- SerializeToString 函数返回 true,ParseFromString 返回 false

最佳答案

我不认为我完全理解你的问题,但无论如何我都会尝试回答。希望这能以某种方式帮助您 :)

是的,这是正常行为。仅当该字段对消息很重要时,才应添加 required。它在语义上是有意义的。 (为什么要跳过必填字段)。为了强制执行此操作,protobuf 不会解析消息。

它看到标有数字 1 的字段是必需的,has_id() 方法返回 false。所以它根本不会解析消息。

developer guide建议不要使用必填字段。

Required Is Forever You should be very careful about marking fields as required. If at some point you wish to stop writing or sending a required field, it will be problematic to change the field to an optional field – old readers will consider messages without this field to be incomplete and may reject or drop them unintentionally. You should consider writing application-specific custom validation routines for your buffers instead. Some engineers at Google have come to the conclusion that using required does more harm than good; they prefer to use only optional and repeated. However, this view is not universal.

还有

Any new fields that you add should be optional or repeated. This means that any messages serialized by code using your "old" message format can be parsed by your new generated code, as they won't be missing any required elements. You should set up sensible default values for these elements so that new code can properly interact with messages generated by old code. Similarly, messages created by your new code can be parsed by your old code: old binaries simply ignore the new field when parsing. However, the unknown fields are not discarded, and if the message is later serialized, the unknown fields are serialized along with it – so if the message is passed on to new code, the new fields are still available. Note that preservation of unknown fields is currently not available for Python

关于c++ - protobuf 必填字段和默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15359669/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com