new_learn: protobuf : array

https://www.reddit.com/r/learnprogramming/comments/3un1lv/help_protobuf_not_sure_if_i_am_using_repeated/

 

User account menu

 

3

 

[Help] [ProtoBuf] [: Not sure if I am using 'repeated' right.

CLOSE

 

3

Posted by

u/ValourValkyria

3 years ago

[Help] [ProtoBuf] [: Not sure if I am using 'repeated' right.

Not a lot of documentation talks about what 'repeated' does in messages.

Scenario: I got multiple replies to the client program from servers. Repeating the whole thing would look hideous and inefficient.

The whole thing is like a struct, in Go I can do such thing: (I got a json example as well but I read the sidebar and I removed it.)

...
type Server struct {
  ServerNo uint32
  IP string
  Port uint32
  Status string
  UserOnline uint32
}
var Server1 = Server{1, "127.0.0.1",12345,"UP",8}
var Server2 = Server{2, "127.0.0.2",12346,"DOWN",0}
...

And I can repeat this thing for all the servers I got.

What I got in my .proto file is this:

...
message ServerDetails {
  message Server {
    uint32 ServerNo = 1; //server no
    string Status = 2; //server up or down?
    uint32 UserOnline = 3; //how many users online?
    string ServerIP  = 4; //server ip?
    uint32 ServerPort = 5; //server port?
  }
  repeated Server server = 1; //how many servers?
}
...

How do you write the return in function then? a for loop?

I am writing Golang, by the way. But any language/solutions are welcomed.

1 Comment

Share

SaveHideReport

100% Upvoted

This thread is archived

New comments cannot be posted and votes cannot be cast

SORT BY

BEST

 

level 1

missblit

2 points·3 years ago·edited 3 years ago

The generated code API is documented here: https://developers.google.com/protocol-buffers/docs/reference/overview

In particular for Go: https://developers.google.com/protocol-buffers/docs/reference/go-generated#repeated

repeated field can occur "zero or more times". This can be thought of as like an arbitrarily sized array.

In C++ you can write a pretty standard for loop to iterate over an embedded message field:

ServerDetails details = ...;
int size = details.server_size();
for(int i = 0; i < size; i++) {
    auto Server* server =  details.server(i);
}

Generating the list on the server side is similar (still C++):

ServerDetails details = ...;
for(Server &s : my_list_of_servers) {
    Server *ptr = details.add_server();
    *ptr = s;
}

I'm still a noob at protocol buffers, so hopefully that's all correct! There's fancier stuff you can do such as reserving X number of elements before adding them, check out the documentation.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值