Mandatory protobuf field and default value

I'm new to protobuf and I started looking at the following trivial example

message Entry {
  required int32 id = 1;
}

used by C ++ code

#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;
}

Even if the id field is required because it has not been set, the size of the serialization buffer is 0 (??).

When I deserialize the message, an error occurs:

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

Is this normal behavior?

Francesco

ps- If I initialize "id" to 0, the behavior is different

pps- Function SerializeToStringreturns true, ParseFromStringreturns false

+5
source share
1 answer

I don’t think I understand your question exactly, but I will still answer. Hope this helps you anyway :)

, . required, . . ( ). , protobuf .

, 1 , has_id() false. .

.

. . - , . , . . Google , , ; . .

. , , , "" , , - . , , . , , , : . , , - , , - . , Python

+4

All Articles