将内部 go struct 数组转换为 protobuf 生成的指针数组
Converting internal go struct array to protobuf generated pointer array
我正在尝试将内部类型转换为 protobuf 生成的类型,但无法转换数组。我是新手,所以我不知道所有可以提供帮助的方法。但这是我的尝试。当 运行 这个代码我得到
panic: runtime error: invalid memory address or nil pointer dereference
[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,
},
}
}
你的 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 文档,因为那里有 Marshal
and Unmarshal
用于解码和编码 protobuf 消息的方法。
我正在尝试将内部类型转换为 protobuf 生成的类型,但无法转换数组。我是新手,所以我不知道所有可以提供帮助的方法。但这是我的尝试。当 运行 这个代码我得到
panic: runtime error: invalid memory address or nil pointer dereference [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,
},
}
}
你的 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 文档,因为那里有 Marshal
and Unmarshal
用于解码和编码 protobuf 消息的方法。