Friday, January 13, 2012

Defaulting message fields in protobuf

Not well documented is the technique for defaulting message fields in protobuf. Say you have a field of message type, named "start" here:

message Complex {
    required int64 real = 1;
    optional int64 imaginary = 2 [default = 0];
}

message Vector {
    required Complex start = 1;
    required int64 length = 2;
}

How to you provide a default value, say at the origin? Like this:

import "google/protobuf/descriptor.proto";

extend google.protobuf.FieldOptions {
    // Pick the field number that is right for you!
    optional Complex complex = 50000;
}

message Vector {
    optional Complex start = 1
    [(complex) = { real: 0 imaginary: 0 }];
    required int64 length = 2;
}

See the Custom Options section for details.

Post a Comment