Skip to content

Allow requiring oneof values #521

@alexander-yevsyukov

Description

@alexander-yevsyukov

In some cases, it is needed to require that one of the fields coming under oneof is set. For example, if we create a user account it can be either person or service field must be set. In order to arrange such a requirement, we can use the following construct:

option (required_field) = "person|service";

// ...

oneof type {
    // The user is a human.
    PersonProfile person = 2;

    // The user is a computer program.
    ServiceProfile service = 3;
}

The problem with this approach is that it's fragile and breaks when we:

  1. rename fields;
  2. add fields under oneof.

We cannot annotate oneof itself, but we cannot reduce the dependency on the content of it by telling the compiler: “We do want one of the things coming under that oneof.” Here's how:

// One of the fields coming under `type` `oneof` must be populated.
option (required).field = "type";

This is still fragile for renaming the oneof itself, but they tend to be more stable, and it's still safer as we refer only one element.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions