首页 > 解决方案 > 将内部 go struct 数组转换为 protobuf 生成的指针数组

问题描述

我正在尝试将内部类型转换为 protobuf 生成的类型,但无法获取要转换的数组。我是新手,所以我不知道所有可以提供帮助的方法。但这是我的尝试。运行此代码时,我得到

恐慌:运行时错误:无效的内存地址或 nil 指针取消引用 [信号 SIGSEGV:分段违规代码 = 0x1 地址 = 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,
    },
  }
}

标签: goprotocol-buffersgrpcgrpc-go

解决方案


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

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

另外,我建议查看 go protobuf 文档,因为那里有用于解码和编码 protobuf 消息的方法MarshalUnmarshal


推荐阅读