62

I have to compose a protobuf message which should have 1 integer variables and a integer array.

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

}

Is my approach correct?

Uwe Allner
  • 3,399
  • 9
  • 35
  • 49
javaMan
  • 6,352
  • 20
  • 67
  • 94

1 Answers1

82

Array is mapped via "repeated":

 repeated int32 data = 4;

Note you might want sint32/uint32. Also note that in all three cases "packed arrays" can be used, which are more efficient;

repeated int32 data = 4 [packed=true];
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • is the packed array concept applicable for double arrays also? – javaMan Sep 13 '11 at 21:05
  • can I write optional repeated double data = 4 [packed = true]; – javaMan Sep 13 '11 at 21:05
  • @Ravi yes, IIRC double is fine. But not strings or sub-messages, IIRC. For full coverage, the language guide goes into more. – Marc Gravell Sep 13 '11 at 21:33
  • in above 4 is tag or array size ? – Raj Jan 25 '17 at 05:46
  • 2
    @Raj tag; the size of the data is determined solely at runtime by how much data is there; there are no fixed sized arrays in protobuf. In the case of "packed", the size (in bytes) is prefixed to the data. – Marc Gravell Jan 25 '17 at 11:16
  • @MarcGravell so packed is a space optimisation. Would un-packed arrays be faster? Just curious if you have any information on the reason you would go one way or the other. – Cameron Lowell Palmer Mar 14 '17 at 06:34
  • 21
    Update: https://developers.google.com/protocol-buffers/docs/proto3 states "In proto3, repeated fields of scalar numeric types use packed encoding by default." – Jason Doucette Jul 31 '17 at 17:52
  • 1
    @Jason very true (I wrote a different reply, then realised the question was purely about .proto schema, not the thing I was talking about) – Marc Gravell Jul 31 '17 at 17:59