【问题标题】:Protobuf default valuesProtobuf 默认值
【发布时间】:2016-12-11 17:37:04
【问题描述】:

我有一个输入登录名的注册表单。当我开始输入时,文本立即发送到检查登录是否可用的服务器。

答案必须是 0 或 1,对或错,取决于我是否会采取进一步行动。 但是 0/false 是默认字段值,它们不会被发送,字段只是保持为空,字段根本不存在(当且仅当字段不等于其默认值时,才会在线发送字段)。

我能用它做什么?我明确需要得到 0 或 1 的答案。当然,我使用的是字符串,但它有问题。

.proto

message InputChecking {
    string login       = 1;
    int32  loginStatus = 2;
    string mail        = 3;
    int32  mailStatus  = 4;
}

message RegistrationRequest {
    ...
}

message WrapperMessage {
    oneof msg {
        InputChecking mes_inputChecking = 1;
        RegistrationRequest mes_registrationRequest = 2;
    }   
}

.cpp

WrapperMessage wm; // protobuf message, is filled with data from the server

const google::protobuf::FieldDescriptor* inputCheckingField = wm.GetDescriptor()->FindFieldByName("mes_inputChecking");

if (wm.GetReflection()->HasField(wm, inputCheckingField)) // if inputCheckingField is
{
    // It says that such a field is, when he receives a message from the server with loginStatus = 0, but there are no fields

    const google::protobuf::FieldDescriptor* loginStatusField = wm.mes_inputchecking().GetDescriptor()->FindFieldByName("loginStatus");

    if (wm.mes_inputchecking().GetReflection()->HasField(wm.mes_inputchecking(), loginStatusField))
    {
            // It is only called when the login is different from 0
            Log("Login status = " + wm.mes_inputchecking().loginstatus()); 
    }
}

【问题讨论】:

  • 您并不清楚您想要的行为。如果您想要一个布尔值,则该值是否在线发送并不重要 - 只是接收到的值与“发送”的值相同。如果您想要三态,请使用枚举。这是proto2还是proto3?
  • @RichardHodges 我一般不会得到值 0,而且他没有字段(loginStatusField)。这是proto3。我会尝试通过枚举,
  • 同样的问题,如果 ListFields 方法的值等于默认值 github.com/google/protobuf/issues/1772,则它不会返回字段
  • 为什么要使用反射接口?只需测试消息中字段的值即可。

标签: c++ protocol-buffers


【解决方案1】:

另一种选择是使用枚举:

enum LoginStatus {
   LOGINSTATUS_INVALID = 0,
   LOGINSTATUS_NOT_AVAILABLE = 1,
   LOGINSTATUS_AVAILABLE = 2
}

这既使代码更具可读性,又允许单独处理第三种状态(响应中缺少字段)。

【讨论】:

    【解决方案2】:

    在阅读this thread 之后,我找到了一种处理可空/默认字段的方法,它可以使用 oneof 包装器。

    message Foo {
      int x = 1;
      oneof v1 { 
         int32 value1 = 2; 
         bool  value2 = 3;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多