'Is there a way to use a proto oneof field as a type in another message?

Suppose I have a proto message like this:

message WorkflowParameters {
  oneof parameters {
    WorkflowAParams a = 1;
    WorkflowBParams b = 2;
  }
}

And I want to have another message where the type of workflow can be specified. Something like this:

message ListWorkflowsRequest {
  // The type of workflows to fetch
  WorkflowParameters.parameters workflow_type = 1;
}

The above doesn't work (it throws "WorkflowParameters.parameters" is not a type.) What's the recommended way of doing this?



Solution 1:[1]

It's not possible. oneof is only a thin syntatic sugar/behavior change, and has no effect on the actual schema. It affects the generated code's behavior, but not the serialized format. In the following example, these two messages are interchangeable and wire-compatible:

message WorkflowParameters {
  oneof parameters {
    WorkflowAParams a = 1;
    WorkflowBParams b = 2;
  }
}
message WorkflowParameters2 {
  WorkflowAParams a = 1;
  WorkflowBParams b = 2;
}

Now, if you just want to specify which part of a oneof will be set, you could theoretically use the generated code constants, and a simple int field:

message ListWorkflowsRequest {
  // The field number of WorkflowParameters that should be filled.
  int32 workflow_type = 1;
}

All language generators should have convenient enough constants created, like WorkflowParameters::A_FIELD_NUMBER for C++.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rafael Lerm