Give your data a name.
Model related fields as one domain value.
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.
#[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);
}Ship the build: false
- 1
Task is a new domain type, not an unlabelled tuple.
- 2
Its title owns its String.
- 3
Accessing fields for formatting borrows the data in this example.
cargo run -p lesson_structs03 Mind the boundary
04 Your next build
Create a Project with name and hours fields, then assert its stored values.
Reveal one possible solution +
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
Which representation best names multiple domain fields?
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.