Skip to content

A oneof groups several fields where at most one can be set at a time. Setting one member clears the others. The group behaves like a tagged union, or a variant in languages that have one, and the generated code stores a single value.

A common use is a value that comes in one of several shapes, such as an Event that is a ClickEvent, a HoverEvent, or a ScrollEvent, with the oneof telling the reader which one arrived. Members always have explicit presence, so a reader can tell which member was set even when its value is zero. A oneof cannot contain repeated fields or maps.

Field 3 is on the wire; field 2 is nowhere to be found.

schema.proto
edition = "2024";

package demo.v1;

message ErrorStatus {
  string message = 1;

  oneof details {
    string stack_trace = 2;
    int32 error_code = 3;
  }
}
Input JSON (editable)
{
  "message": "invalid argument",
  "errorCode": 3
}
ProtoJSON

Compiling the schema...

Next

Generating Code

Turning .proto files into typed APIs with buf generate or protoc: configuring plugins, and using the generated code to build and serialize messages.