Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ MODEL THE DOMAIN
BUILD NOTE 14 / 53

Give your data a name.

Model related fields as one domain value.

BY NAVAN SAMI◷ 7 MIN READFOUNDATIONSRUST 2024

01 Understand the contract

A struct groups named fields into a new type. Ownership rules apply to each field: a String field is owned, while a reference field borrows and needs a lifetime relationship. Start with owned fields when a value should stand independently. Struct update syntax can move fields from the original, so do not assume the original remains fully usable. Deriving Debug gives an inspection format; a public-facing report can use a deliberate formatter instead.

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/structs/src/main.rs
#[derive(Debug)]
struct Task {
    title: String,
    complete: bool,
}
fn main() {
    let task = Task {
        title: String::from("Ship the build"),
        complete: false,
    };
    println!("{}: {}", task.title, task.complete);
}
↳ EXPECTED OUTPUT
Ship the build: false
  1. 1

    Task is a new domain type, not an unlabelled tuple.

  2. 2

    Its title owns its String.

  3. 3

    Accessing fields for formatting borrows the data in this example.

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

03 Mind the boundary

04 Your next build

A SMALL MISSION

Create a Project with name and hours fields, then assert its stored values.

Reveal one possible solution +
solutions/structs/src/main.rs
struct Project {
    name: String,
    hours: u32,
}
fn main() {
    let p = Project {
        name: "Lab".into(),
        hours: 8,
    };
    assert_eq!(p.name, "Lab");
    assert_eq!(p.hours, 8);
}

05 Check your reasoning

QUICK SIGNAL CHECK

Which representation best names multiple domain fields?

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.