Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ ASYNC & SYSTEM BOUNDARIES
BUILD NOTE 48 / 53

Data crossing the wire needs a contract.

Separate transport formats from valid domain values.

BY NAVAN SAMI◷ 9 MIN READADVANCEDRUST 2024

01 Understand the contract

Serialization converts typed data into a transport representation; deserialization performs the reverse. Serde derives these operations for compatible types, with serde_json supplying JSON encoding. A syntactically valid JSON document can still violate your domain rules. Deserialize into an input type, validate length, range, and required relationships, then construct a domain value. The Axum task API cookbook demonstrates this full path with JSON input and status codes. Never build JSON or SQL by concatenating untrusted text.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/serialization/src/main.rs
#[derive(Debug, PartialEq)]
struct Title(String);
impl Title {
    fn parse(raw: &str) -> Result<Self, &'static str> {
        let value = raw.trim();
        if value.is_empty() || value.chars().count() > 80 {
            Err("title must contain 1–80 characters")
        } else {
            Ok(Self(value.to_owned()))
        }
    }
}
fn main() {
    let title = Title::parse("  Build  ").unwrap();
    println!("{}", title.0);
    assert!(Title::parse(" ").is_err());
}
↳ EXPECTED OUTPUT
Build
  1. 1

    Parsing transport text and validating domain meaning are separate steps.

  2. 2

    Trim defines the accepted normalization policy.

  3. 3

    The owned Title can be passed beyond the input buffer’s lifetime.

From the extracted rust-workbench folder
cargo run -p lesson_serialization

03 Mind the boundary

04 Your next build

A SMALL MISSION

Validate a username of 3–16 ASCII alphanumeric characters, rejecting spaces.

Reveal one possible solution +
solutions/serialization/src/main.rs
fn valid(s: &str) -> bool {
    (3..=16).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_alphanumeric())
}
fn main() {
    assert!(valid("navan7"));
    assert!(!valid("ab"));
    assert!(!valid("a b"));
    assert!(!valid("ééé"));
}

05 Check your reasoning

QUICK SIGNAL CHECK

Does successful JSON deserialization guarantee valid business data?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.