expression

Protocol Buffers: adding a field and handling old messages

Adding a new field using an unused number can preserve binary compatibility, but old messages do not contain the new value. The local model shows a new application explicitly handling a missing stock field. Binary compatibility does not guarantee JSON or business compatibility. Expected stdout (not executed): 7: unknown 7: 0 Common mistake: Making a new field immediately mandatory in application validation while older clients still omit it.

Formal Syntax & Structure

rust syntaxrust
optional uint32 stock = 3;

Working Example

Example Snippetrust
fn main() {    struct Item { id: u64, stock: Option<u32> }    let old_message = Item { id: 7, stock: None };    let new_message = Item { id: 7, stock: Some(0) };    for item in [old_message, new_message] {        match item.stock {            None => println!("{}: unknown", item.id),            Some(n) => println!("{}: {n}", item.id),        }    }}
Rust Reference