将内部go结构数组转换为protobuf生成的指针数组

问题描述 投票:0回答:1

我正在尝试将内部类型转换为protobuf生成的类型,我无法让数组转换。我是新手,所以我不知道所有可能有用的方法。但这是我的尝试。当我运行此代码时,我得到了

panic:运行时错误:无效的内存地址或nil指针取消引用[signal SIGSEGV:segmentation violation code = 0x1 addr = 0x8 pc = 0x86c724]

以及许多其他字节数据。我想知道将内部结构转换为protobufs的最佳方法是什么。我认为我最常遇到的问题是protobuf生成的代码是指针。

原型定义

message GameHistory {
  message Game {
    int64 gameId = 1;
  }

  repeated Game matches = 1;
  string username = 2;
}

message GetRequest {
  string username = 1;
}

message GetGameResponse {
  GameHistory gameHistory = 1;
}

去代码

// GameHistory model
type GameHistory struct {
  Game []struct {
    GameID     int64  `json:"gameId"`
  } `json:"games"`
  UserName   string `json:"username"`
}

func constructGameHistoryResponse(gameHistory models.GameHistory) *pb.GetGameResponse {

  games := make([]*pb.GameHistory_Game, len(gameHistory.Games))
  for i := range matchHistory.Matches {
    games[i].GameID = gameHistory.Games[i].GameID
  }

  res := &pb.GetGameResponse{
    GameHistory: &pb.GameHistory{
      Games:    games,
    },
  }
}
go protocol-buffers grpc grpc-go
1个回答
1
投票

你的games切片用nil值初始化,因为它的类型为[]*pb.GameHistory_Game(指向pb.GameGistory_Game的指针切片 - 指针的init值为nil)。您想要访问这些元素的GameID属性。您应该创建它们:

for i := range matchHistory.Matches {
    games[i]=&pb.GameHistory{GameID: gameHistory.Games[i].GameID}
}

此外,我建议看一下go protobuf文档,因为你有MarshalUnmarshal方法来解码和编码protobuf消息。

© www.soinside.com 2019 - 2024. All rights reserved.