34
message Person {
  required Empid = 1 [default = 100];
  required string name = 2 [default = "Raju"];
  optional string occupation = 3;
  repeated string snippets = 4;
}

Can I give the default values as mentioned above?

1
  • I think you missed a ; on end of the Empid field :) Commented Jun 10, 2020 at 20:44

2 Answers 2

42

For proto3, custom default values are disallowed.

Sign up to request clarification or add additional context in comments.

3 Comments

If I want custom default values, what should I do?
@ch271828n, one option could be to use proto2. Another might be to write custom add-ons.
can somebody link to the rationale for why it was removed? for the above string field name, I believe you can differentiate between an explicitly set empty-string and a defaulted empty-string with the (java/grpc --presumably similar on other platforms) hasName() method. Is this the suggested work-around?
16

Update: The below answer is for proto2 only, proto3 doesn't allow custom default values.

Yes, you can give default values as you had written. default is optional for required, but for optional you have to mention the default values else type specific value is automatically assigned. Moreover you forgot to mention the type for Empid.

protobuf language guide states that

If the default value is not specified for an optional element, a type-specific default value is used instead: for strings, the default value is the empty string. For bools, the default value is false. For numeric types, the default value is zero. For enums, the default value is the first value listed in the enum's type definition. This means care must be taken when adding a value to the beginning of an enum value list.

1 Comment

To clarify, I can not seem to set a different default value for strings. So is that still not possible. They are always just defaulted to empty string?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.