How to define an optional field in protobuf 3

前端 未结 9 1419
无人及你
无人及你 2020-12-22 18:14

I need to specify a message with an optional field in protobuf (proto3 syntax). In terms of proto 2 syntax, the message I want to express is something like:

         


        
9条回答
  •  臣服心动
    2020-12-22 18:50

    Another way to encode the message you intend is to add another field to track "set" fields:

    syntax="proto3";
    
    package qtprotobuf.examples;
    
    message SparseMessage {
        repeated uint32 fieldsUsed = 1;
        bool   attendedParty = 2;
        uint32 numberOfKids  = 3;
        string nickName      = 4;
    }
    
    message ExplicitMessage {
        enum PARTY_STATUS {ATTENDED=0; DIDNT_ATTEND=1; DIDNT_ASK=2;};
        PARTY_STATUS attendedParty = 1;
        bool   indicatedKids = 2;
        uint32 numberOfKids  = 3;
        enum NO_NICK_STATUS {HAS_NO_NICKNAME=0; WOULD_NOT_ADMIT_TO_HAVING_HAD_NICKNAME=1;};
        NO_NICK_STATUS noNickStatus = 4;
        string nickName      = 5;
    }
    

    This is especially appropriate if there is a large number of fields and only a small number of them have been assigned.

    In python, usage would look like this:

    import field_enum_example_pb2
    m = field_enum_example_pb2.SparseMessage()
    m.attendedParty = True
    m.fieldsUsed.append(field_enum_example_pb2.SparseMessages.ATTENDEDPARTY_FIELD_NUMBER)
    

提交回复
热议问题