Getting Expected top-level statement (e.g. "message") when trying to create 2D array in Protobuf

3.1k Views Asked by At

I am using trying to create a 2d array in .proto file like this:

message Foo {
    repeated int32 items = 1;
}

repeated Foo items= 1;

but on generating the .pb.go file, getting the error for this line repeated Foo items= 1;

Getting Expected top-level statement (e.g. "message")

Has anyone ever came across this error?

Please let me know how could we resolve this issue?

1

There are 1 best solutions below

0
On BEST ANSWER

You cannot have a field at the top level, everything should be enclosed in a message or enum. So in your case you should have something like:

message Foo {
    repeated int32 items = 1;
}

message Bar {
    repeated Foo items = 1;
}

Then you will be able to set the items by doing the following:

&pb.Bar {
    Items: []*pb.Foo {
        { Items: []int32{1, 2, 3, 4, 5, 6} },
        { Items: []int32{7, 8, 9, 10, 11, 12} },
    },
}

where pb is the name for the import of the package you defined in your proto file. Eg:

proto:

option go_package = "example.com/m/proto";

go:

import pb "example.com/m/proto"