Skip to content

If you have a message with multiple fields where only one can be set at a time, you can enforce this behavior and save memory using the oneof keyword.

Setting any field within the oneof automatically clears all other fields in that same oneof. This is Protobuf's equivalent to a tagged union or variant.

A common use is polymorphism: an Event that could be a ClickEvent, HoverEvent, or ScrollEvent.

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

Services

Defining RPC interfaces with the Protobuf service keyword: unary and streaming methods, and how frameworks like gRPC and ConnectRPC generate clients and servers.