Oneof Fields in Protobuf

Use oneof to define mutually exclusive fields in protobuf. Learn about memory optimization, setting behavior, and common patterns like union types and polymorphism.

Enums & Oneof

Detailed Explanation

Mutually Exclusive Fields with Oneof

The oneof construct defines a set of fields where at most one can be set at a time. Setting any field in a oneof automatically clears all other fields in the same group. This is protobuf's approach to union types.

syntax = "proto3";

message PaymentMethod {
  string id = 1;

  oneof method {
    CreditCard credit_card = 2;
    BankAccount bank_account = 3;
    DigitalWallet digital_wallet = 4;
    Cryptocurrency crypto = 5;
  }
}

message CreditCard {
  string number = 1;
  string expiry_month = 2;
  string expiry_year = 3;
  string cardholder_name = 4;
}

message BankAccount {
  string account_number = 1;
  string routing_number = 2;
  string bank_name = 3;
}

message DigitalWallet {
  string provider = 1;
  string wallet_id = 2;
}

message Cryptocurrency {
  string currency = 1;
  string wallet_address = 2;
  string network = 3;
}

How Oneof Works

  1. At most one field: Setting a oneof field automatically clears any previously set field in the group.
  2. Case detection: Generated code includes a which_* or *_case() method to determine which field is currently set.
  3. Memory sharing: All fields in a oneof share memory in C++, reducing the message's memory footprint.
  4. Cannot be repeated: You cannot use repeated with a oneof field.

Common Patterns

Polymorphic messages — representing different variants of a concept:

message Shape {
  oneof shape {
    Circle circle = 1;
    Rectangle rectangle = 2;
    Triangle triangle = 3;
  }
}

Result types — representing success or failure:

message OperationResult {
  oneof result {
    SuccessResponse success = 1;
    ErrorResponse error = 2;
  }
}

Wire Format

On the wire, a oneof is encoded as a regular field — only the set field appears. The receiver uses the field number to determine which variant was sent.

Use Case

Implementing payment method selection, notification channel routing (email vs SMS vs push), authentication credential types, or any API field where exactly one of several options must be provided.

Try It — Protobuf Definition Parser

Open full tool