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条)

报告相同问题?

悬赏问题

  • ¥50 comsol温度场仿真无法模拟微米级激光光斑
  • ¥15 上传图片时提交的存储类型
  • ¥15 Ubuntu开机显示器只显示kernel,是没操作系统(相关搜索:显卡驱动)
  • ¥15 VB.NET如何绘制倾斜的椭圆
  • ¥15 在rhel8中安装qemu-kvm时遇到“cannot initialize crypto:unable to initialize gcrypt“报错”
  • ¥15 arbotix没有/cmd_vel话题
  • ¥20 找能定制Python脚本的
  • ¥15 odoo17的分包重新供应路线如何设置?可从销售订单中实时直接触发采购订单或相关单据
  • ¥15 用C语言怎么判断字符串的输入是否符合设定?
  • ¥15 通信专业本科生论文选这两个哪个方向好研究呀