Troskyvs
Troskyvs

Reputation: 8047

Why protobuf both required/optional field accepts "default" value, I expect only "optional" should

The google protobuf allow me to write proto code like this:

syntax="proto2";
message hello
{
    optional int32 id=1;
    required string str=2[default="abc"];
    optional int32 op=3 [default=15];
}

It compiles, no problem. I don't just quite understand that, for "optional" field, when there's no value specified, the decode stream return me the default value, it's OK. But what about the "required" field, it cann't be empty, so how its "default" is also valid? In what scenario?

Upvotes: 2

Views: 4005

Answers (1)

Kenton Varda
Kenton Varda

Reputation: 45191

The "default" value is the value returned by the field's getter when the field has not been set yet. When you create a new message object, initially, none of the fields are set -- even required fields. So, the default value is what the getter will return if you call it immediately.

Granted, this is not particularly useful for required fields, but there didn't seem to be any reason to prohibit it.

Upvotes: 4

Related Questions