expression

Versioned schema envelope

Represent the schema version explicitly. Validate the version before consuming the payload; future versions need deliberate migration rather than a guessed interpretation. This example uses external crates; see the staged Cargo manifest. Expected stdout (not executed): 8 unsupported version Common mistake: Treating an unknown version as the latest known schema.

Formal Syntax & Structure

rust syntaxrust
struct Envelope { version: u8, payload: T }

Working Example

Example Snippetrust
fn main() {    #[derive(serde::Deserialize)]    struct Envelope { version: u8, payload: serde_json::Value }    fn read(s: &str) -> Result<u64, &'static str> {        let e: Envelope = serde_json::from_str(s).map_err(|_| "invalid envelope")?;        if e.version != 1 { return Err("unsupported version"); }        e.payload.get("count").and_then(|v| v.as_u64()).ok_or("invalid count")    }    println!("{}", read(r#"{"version":1,"payload":{"count":8}}"#).unwrap());    println!("{}", read(r#"{"version":2,"payload":{}}"#).unwrap_err());}
Rust Reference