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

固定大小的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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dqs66973 2018-10-23 13:31

    You are calling len() on a byte array. It is going to count the number of elements in that array, and return it.

    If you have just instantiated a new, empty, protobuf pointer object with nothing inside, the marshaled byte array will not hold any data -- thus why you're getting 0.

    I'm quite unsure what you're wanting it to return instead. Could you clarify your question a bit more with what you're wanting the output to be? I can maybe better answer your question.

    评论
    解决 无用
    打赏 举报