hakunami
hakunami

Reputation: 2441

How to set default value to a customed google protobuf type?

I have a google protobuf structure:

message ResourceProto{
    optional int32 memory = 0;
    optional int32 core = 1;
}

And I have another structure:

message AnotherProto{
    optional ResourceProto resource = 0 [default to ResourceProto(100,1)];
    ....
}

I know how to set default value to normal type like int, String, Bool, but how to assign default value to customed structure, what is the syntax? Say, set the default value of resource in AnotherProto to memory = 100 and core = 1?

Upvotes: 2

Views: 9241

Answers (1)

alavrik
alavrik

Reputation: 2161

Protocol Buffers doesn't support default values for fields of non-primitive types. Not sure why exactly, but I would assume this is because it is rarely needed in practice and tricky to implement:

  • Arbitrary default values are rather difficult to self-describe in a consistent and portable way. Essentially you need to have a notion of a dynamically-typed any type, which is not supported by Protobuf2. Instead, they represent defaults as optional string default_value with some implementation-dependent syntax for the values.
  • When you allow this in the definition language, you need to introduce syntax for structured default values. This is slightly more complicated than supporting syntax for primitive values alone.
  • Depending on a target language, it may not be quite clear how to handle such default values at runtime with regard to dynamic object allocation and ownership. The safest option would involve copying which may result in unexpected performance hit.

That said, fundamentally, it can be done. For instance, I've implemented support for arbitrary defaults in piqi and it works well in OCaml and Erlang.

Upvotes: 2

Related Questions