dongqi8863 2018-10-23 13:02
浏览 65
已采纳

固定大小的golang protobuf元帅空结构

I hava a protobuf struct Data

in .proto:

message Data {
    uint64 ID = 1;
    uint32 GUID = 2;
}

in golang

b, err := proto.Marshal(&pb.Data{})
if err != nil {
    panic(err)
}
fmt.Println(len(b))

I got 0 length!

How can I make proto.Marshal always return fixed size no matter what pb.Data is?

ps.

pb.Data only contains int64 and int32

  • 写回答

2条回答 默认 最新

  • douchui4459 2018-10-23 17:27
    关注

    There are two issues here

    1) protobuf uses varint encoding for integers, so the size depends on the value, see this link

    2) zero value fields are not transmitted by default, so because the two integers are zero, even their field identifiers are not sent. I'm actually not sure there's even an option to send zero values looking at the docs

    if you set them both to 1, you will have more than zero bytes, but it still won't be fixed in length, depending on range of the values

    so, there's no real way to enforce fixed size in protobuf messages in general

    if you want fixed length messages, you are probably better off using direct structs-on-the-wire type encoding, but then that's harder for language interop as they'd all have to define the same message and you'd lose easy message migrations and all the cool stuff that protobuf gives.

    Cap'n Proto might have an option for fixed size structs, but they also generally compress which will, once again, produce variable length messages.

    If you describe the problem you are trying to ultimately solve, we may be able to suggest other alternatives.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?