User account menu
3
[Help] [ProtoBuf] [: Not sure if I am using 'repeated' right.
CLOSE
3
Posted by
[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.
Share
SaveHideReport
100% Upvoted
This thread is archived
New comments cannot be posted and votes cannot be cast
SORT BY
BEST
level 1
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
A 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.