syntax = "proto3"; enum SetGet { SET = 0; GET = 1; } message State { SetGet setget = 1; double x = 2; double y = 3; double depth = 4; double yaw = 5; double pitch = 6; double roll = 7; }
我使用protoc将文件编译为Python _pb2文件,然后尝试运行以下测试脚本:
import filename_pb2 as pb state = pb.State() state.x = 0 state.y = 0 state.depth = 0 state.yaw = 0 state.pitch = 0 state.roll = 0 state.setget = pb.SET print("State: {}".format(state)) state2 = pb.State() state2.ParseFromString(state.SerializeToString()) print("State2: {}".format(state2))
当我运行它时,打印以下输出:
State: State2:
似乎没有设置任何东西,或零值以某种方式被忽略.
但是,当我将值(x,y,深度等)更改为非零值(例如0.1)时,我得到以下预期结果:
State: x: 0.1 y: 0.1 depth: 0.1 yaw: 0.1 pitch: 0.1 roll: 0.1 State2: x: 0.1 y: 0.1 depth: 0.1 yaw: 0.1 pitch: 0.1 roll: 0.1
即使数字被打印出来,由于某种原因,枚举仍然不是.
为什么这会发生在protobufs上?默认情况下是double类型0,因此protobuf序列化程序会忽略它们来节省空间吗?那么,为什么在解析State2时它们没有被恢复?我错过了文档中的某些内容吗?提前致谢!
– 蒂姆
是,0是默认值.在 the documentation中明确提到了这种情况:Note that for scalar message fields, once a message is parsed there’s no way of telling whether a field was explicitly set to the default value (for example whether a boolean was set to false) or just not set at all: you should bear this in mind when defining your message types. For example, don’t have a boolean that switches on some behaviour when set to false if you don’t want that behaviour to also happen by default. Also note that if a scalar message field is set to its default, the value will not be serialized on the wire.