doulao1934 2019-03-27 16:05
浏览 621
已采纳

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

I'm trying to convert an internal type to the protobuf generated type and I can't get the array to convert. I'm new to go so I don't know all the methods that could help. But this is my attempt. When run this code I get

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

along with a lot other byte data. I'm wondering what the best way to convert internal structs to the protobufs is. I think I'm having the most trouble with the protobuf generated code being pointers.

Proto Definitions

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

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

message GetRequest {
  string username = 1;
}

message GetGameResponse {
  GameHistory gameHistory = 1;
}

Go Code

// 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,
    },
  }
}
  • 写回答

1条回答 默认 最新

  • dongren5293 2019-03-27 19:42
    关注

    Your games slice is initialized with nil values, as it's of type []*pb.GameHistory_Game (slice of pointers to pb.GameGistory_Game - init value for pointer is nil). You want to access the GameID property of those elements. You should create them instead :

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

    Also, I recommend taking a look over the go protobuf documentation, as you have the Marshal and Unmarshal methods there for decoding and encoding protobuf messages.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同