If you want to create an associative map as part of your data definition, protocol buffers provides a handy shortcut syntax:
如果你想创建一个关联map作为你数据定义的一部分,protocol buffers 提供了一个便捷的快捷语法:
map<key_type, value_type> map_field = N;
...where the key_type can be any integral or string type (so, any scalar type except for floating point types and bytes). Note that enum is not a valid key_type. The value_type can be any type except another map.
其中key_type可以是任意整型或字符串类型(所以,任何标量类型除了浮点型和字节类型)。注意枚举类型不是可用的key_type。value_type可以是除了其他map类型的任意类型。
So, for example, if you wanted to create a map of projects where each Project message is associated with a string key, you could define it like this:
所以,举个例子,如果你想创建一个map类型的protject,每个Projectmessage是有一个字符串类型的键,可以像这样来定义它:
map<string, Project> projects = 3;
Map fields cannot be
repeated.
Map字段不能是repeated(重复的)。Wire format ordering and map iteration ordering of map values are undefined, so you cannot rely on your map items being in a particular order.
map值的线路格式命令和map迭代命令是未定义的,所以你不能将你的map项进行特殊排序。When generating text format for a
.proto, maps are sorted by key. Numeric keys are sorted numerically.
当把.proto文件生成文本格式时,map是按照可以进行排序的。数字键是按照数字化(大小)进行排序。When parsing from the wire or when merging, if there are duplicate map keys the last key seen is used. When parsing a map from text format, parsing may fail if there are duplicate keys.
从线路(网络)中解析或合并时,如果有重复映射键,则使用最后一个看到的键。当从text格式解析map时,如果有重复键的话解析可能会失败。If you provide a key but no value for a map field, the behavior when the field is serialized is language-dependent. In C++, Java, Kotlin, and Python the default value for the type is serialized, while in other languages nothing is serialized.
如果你为一个映射字段提供了一个没有值的键,字符如何解析是取决于语言的。在C++, Java, Kotlin, 和Python中,默认值会被序列化,其他语言中则不会被序列化。
The generated map API is currently available for all proto3 supported languages. You can find out more about the map API for your chosen language in the relevant API reference.
生成映射的API对于proto3所支持的语言现在都是可用的。你可以在API 参考中查看更多有关你所选语言的map API的信息。
Backwards compatibility - 向下兼容
The map syntax is equivalent to the following on the wire, so protocol buffers implementations that do not support maps can still handle your data:
在线路(网络)中map语法和下面的写法等价,所以虽然protocol buffers实现不支持映射,但是仍然可以处理你的数据:
message MapFieldEntry {
key_type key = 1;
value_type value = 2;
}
repeated MapFieldEntry map_field = N;
Any protocol buffers implementation that supports maps must both produce and accept data that can be accepted by the above definition.
任何protocol buffers支持映射的实现都必须产生和接受上边定义所能接受的数据。