go - 将内部 go struct 数组转换为 protobuf 生成的指针数组

标签 go protocol-buffers grpc grpc-go

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

panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation code=0x1 addr=0x8 pc=0x86c724]

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

原型(prototype)定义

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,
    },
  }
}

最佳答案

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

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

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

关于go - 将内部 go struct 数组转换为 protobuf 生成的指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55381710/

相关文章:

json - Go - JSON解码器没有初始化我的结构

protocol-buffers - 减少 protobuf 消息大小的最佳实践?

ssl - 如何使用 TLS 连接到 GRPC?

go - go grpc-go健康检查如何实现?

ios - Protocol Buffers Swift 生成图像未找到

GRPC 客户端阻塞 vs 异步 stub 推荐

amazon-web-services - 在 golang 中订阅 SNS 主题和/或 SQS 队列?

docker - 使用 Golang 和 Docker 导入外部包时构建失败

go - 模板不必要地将 `<` 转义为 `&lt;` 但不是 `>`

java - Protobuf-net 和 .proto 文件?