Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I define a constant string in protobuf?

Tags:

I use protobuf's enums to share values between a C++ app and a Java app. This way, the same (int) values are shared between languages and the values are available at compile time. Can I do something similar with a string by somehow defining it in the common .proto file?

like image 248
ytoledano Avatar asked Feb 29 '16 11:02

ytoledano


People also ask

How do you define a constant string?

A constant string is declared when it is required to be immutable, which means once any data is defined as constant, it cannot be changed. Constant strings are declared as private static final String in Java. These strings are initialized in the class and used in the different methods.

How does Protobuf serialize string?

The Protobuf serialization mechanism is given through the protoc application, this compiler will parse the . proto file and will generate as output, source files according to the configured language by its arguments, in this case, C++. You can also obtain more information about, reading the section compiler invocation.

Can Protobuf string be null?

Protobuf treats strings as primitive types and therefore they can not be null.

How do I set default value in Protobuf?

For bool s, 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 Answers

Not really.

There are a few hacks you can use. Neither is a great fit, and (I think) both are going away in proto3:

  • Define a message with a string field and give it a default value which is your constant value. However, Protobuf 3 is removing default values, apparently.
  • Use "custom options", which should probably have been called "annotations" as they are much like annotations in Java or other languages. You can declare an annotation of type string, then annotate some dummy declaration with your annotation and use the constant value. However, custom options are based on extensions which are also removed in proto3, so I assume custom options have been removed too. (This is the answer offered here: https://stackoverflow.com/a/11486640/2686899.)

FWIW, Cap'n Proto, an alternative to protocol buffers, does support constants. (Disclosure: I am the author of Cap'n Proto as well as most of Google's Protobuf v2.)

like image 152
Kenton Varda Avatar answered Sep 20 '22 01:09

Kenton Varda