我正在尝试将内部类型转换为 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 文档,因为您有 Marshal
和 Unmarshal
那里有用于解码和编码 protobuf 消息的方法。
关于go - 将内部 go struct 数组转换为 protobuf 生成的指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55381710/