如何在 protobuf 消息中添加一个 int 数组

64

我需要组装一个protobuf消息,其中应该包含1个整数变量和一个整数数组。

package protobuf;

message myProto {

optional uint32 message_id =1;
optional int update = 2;
//here I have to add a array of integers
//can I write like     optional int[] array =3;
//or should I use      optional repeated array;
//where array is another message with int variable

}

我的做法正确吗?

1个回答

83

使用"repeated"对数组进行了映射:

 repeated int32 data = 4;

注意,您可能需要sint32 / uint32。另请注意,在所有三种情况下都可以使用“紧凑数组”,这更有效率。

repeated int32 data = 4 [packed=true];

紧凑数组的概念是否适用于双精度数组? - javaMan
2
@Raj 标记;数据的大小仅在运行时由数据量决定;在 protobuf 中没有固定大小的数组。在“packed”情况下,数据的大小(以字节为单位)会作为前缀添加到数据中。 - Marc Gravell
@MarcGravell,压缩是一种空间优化。非压缩数组会更快吗?只是好奇你是否有任何关于选择哪种方式的原因的信息。 - Cameron Lowell Palmer
21
更新:https://developers.google.com/protocol-buffers/docs/proto3 上写道:“在 proto3 中,标量数值类型的重复字段默认使用紧缩编码。” - Jason Doucette
1
@Jason 非常正确(我写了另一个回复,然后意识到问题纯粹是关于.proto模式,而不是我所谈论的那个东西) - Marc Gravell
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接