Search code examples
gostructprotocol-buffers

How to initialize, import message from protobuf as array in Golang


I have a protobuf file as follows:

message Lesson {
  int64 UserId = 1;
  int32 CourseId = 2;
  int32 LessonId = 3;
  LessonStatus Status = 4;
  google.protobuf.Timestamp DateSubmitted = 5;
  
  message Question {
    string QuestionId = 1;
    string StudentAnswer = 2;
    QuestionStatus Status = 3;
    string SupComment = 4;

  }

  repeated Question Questions = 6;

}

}

The protobuf file is imported as api.

Creating a single object of Lesson_Question is simple, with &api.Lesson_Question{}, but I am trying to create a slice of Questions. I have been Googling for a while and don't find any documentation on this.

I have tried all sorts of combinations, such as:

  • questions := []*api.Lesson_Question
  • questions := []&api.Lesson_Question
  • questions := &[]api.Lesson_Question
  • questions := *[]api.Lesson_Question
  • questions := []api.Lesson_Question

but all give an error.

Any assistance or pointers would be appreciated!


Solution

  • If you are using go-grpc, the Questions member will be generated as []*api.Lesson_Question. To declare a literal:

    empty_questions:=[]*api.Lesson_Question{}
    questions:=[]*api.Lesson_Question{&api.Lesson_Question{QuestionId:"q1"},
      &api.Lesson_Question{QuestionId:"q2"}}