How to define an optional field in protobuf 3

前端 未结 9 1413
无人及你
无人及你 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:51

    To expand on @cybersnoopy 's suggestion here

    if you had a .proto file with a message like so:

    message Request {
        oneof option {
            int64 option_value = 1;
        }
    }
    

    You can make use of the case options provided (java generated code):

    So we can now write some code as follows:

    Request.OptionCase optionCase = request.getOptionCase();
    OptionCase optionNotSet = OPTION_NOT_SET;
    
    if (optionNotSet.equals(optionCase)){
        // value not set
    } else {
        // value set
    }
    

提交回复
热议问题