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 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line