expression

Optional fields and JSON null

For a typical derived struct, absent optional fields and explicit null both decode to None. A present field of the wrong type can still fail. Distinct absence and null require a deliberate representation. Serde and serde_json are external crates; use the staged Cargo manifest. Expected stdout (not executed): None None Some("hi") Common mistake: Assuming Option automatically preserves the distinction between missing and null.

Formal Syntax & Structure

rust syntaxrust
Option<T> with derived Deserialize

Working Example

Example Snippetrust
fn main() {    #[derive(serde::Deserialize)]    struct Note { text: Option<String> }    for input in ["{}", r#"{"text":null}"#, r#"{"text":"hi"}"#] {        let n: Note = serde_json::from_str(input).unwrap();        println!("{:?}", n.text.as_deref());    }}
Rust Reference