Reading — step 1 of 5
Read
~1 min readWire Format
Maps and Oneof
Maps are syntactic sugar
map<K, V> m = N; is NOT a new wire type. It compiles to:
message MapFieldEntry {
optional K key = 1;
optional V value = 2;
}
repeated MapFieldEntry m = N;
That means on the wire a map is just a repeated field of length-delimited
sub-messages. A parser that doesn't recognize the field skips it like any
other LEN field. Implementations agree that:
- Keys can be any integral or string type (not float, bytes, or message).
- Wire order is unspecified — never rely on iteration order.
- Duplicate keys: the last occurrence wins.
- Maps cannot be
repeated,oneof, or have field presence.
Oneof
oneof declares a union — at most one field in the set can be set at a
time. Setting one automatically clears any other. On the wire it's just the
fields encoded normally; the parser tracks "which field was last seen" for
that oneof.
message Update {
oneof payload {
string text = 1;
bytes binary = 2;
int32 counter = 3;
}
}
Key properties:
- Fields in a oneof share field presence semantics even in proto3.
- Setting one clears all others on the sender; on the receiver, the last-encoded field wins.
- Removing a field from a oneof is dangerous — you may inherit junk state from old messages.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…