我可以在 protobuf 中定义一个常量字符串吗?
Can I define a constant string in protobuf?
我使用 protobuf 的枚举在 C++ 应用程序和 Java 应用程序之间共享值。这样,相同的 (int
) 值在语言之间共享,并且这些值在编译时可用。我可以通过在公共 .proto
文件中以某种方式定义它来对字符串做类似的事情吗?
不是真的。
您可以使用一些技巧。两者都不太合适,而且(我认为)两者都将在 proto3 中消失:
- 定义一个带有字符串字段的消息,并为其指定一个默认值,即您的常量值。但是,Protobuf 3 显然正在删除默认值。
- 使用"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: 。)
FWIW,Cap'n Proto,protocol buffers 的替代品,确实支持常量。 (披露:我是 Cap'n Proto 的作者,也是 Google 的 Protobuf v2 的大部分作者。)
我使用 protobuf 的枚举在 C++ 应用程序和 Java 应用程序之间共享值。这样,相同的 (int
) 值在语言之间共享,并且这些值在编译时可用。我可以通过在公共 .proto
文件中以某种方式定义它来对字符串做类似的事情吗?
不是真的。
您可以使用一些技巧。两者都不太合适,而且(我认为)两者都将在 proto3 中消失:
- 定义一个带有字符串字段的消息,并为其指定一个默认值,即您的常量值。但是,Protobuf 3 显然正在删除默认值。
- 使用"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: 。)
FWIW,Cap'n Proto,protocol buffers 的替代品,确实支持常量。 (披露:我是 Cap'n Proto 的作者,也是 Google 的 Protobuf v2 的大部分作者。)