Chapter 21: Advanced Protobuf — Oneof, Maps, Any, Wrappers

Oneof (Exactly One Field Set)

message Event {
  string id = 1;
  oneof payload {
    UserCreated user_created = 2;
    OrderPlaced order_placed = 3;
    PaymentFailed payment_failed = 4;
  }
}

Maps

message Session {
  map<string, string> attributes = 1;  // key-value pairs
  map<int32, Rule> rules = 2;        // ID → Rule mapping
}

google.protobuf.Any (Dynamic Typing)

import "google/protobuf/any.proto";
message Envelope {
  string type = 1;
  google.protobuf.Any payload = 2;  // can hold any message type
}

Wrapper Types (Nullable Scalars)

import "google/protobuf/wrappers.proto";
message User {
  string name = 1;
  google.protobuf.Int32Value age = 2;  // nullable! can distinguish 0 from "not set"
}