By the end of this lesson
Group related data and define a method that borrows it.
Before you start
- Rust 1.90.0 or later, a terminal and a plain-text editor. Examples were tested with Rust 1.90.0, Edition 2024 on Linux.
- Complete lesson 13, or be comfortable explaining and running its examples.
Three words to know
- Struct
- A named data type with fields.
- Field
- One named part of a struct value.
- Method
- A function associated with a type and often a self parameter.
1. Understand the idea
A struct gives a meaningful name to related values. Its field names are clearer than remembering tuple positions. impl groups operations associated with the type. A method taking &self borrows the value for inspection; &mut self permits modification and self by value takes ownership. Choose that receiver according to the operation’s purpose.
2. Save, run and observe
Save this complete program as lesson.rs in a fresh practice folder. It replaces that lesson file only; keep earlier examples separately. Compile it with rustc, then run the executable. Rust source goes in the editor; rustc and cargo commands go in the terminal.
struct Task { title: String, done: bool }
impl Task {
fn label(&self) -> &str { if self.done { "closed" } else { "open" } }
}
fn main() {
let task = Task { title: String::from("Read"), done: false };
println!("{}: {}", task.title, task.label());
}
What you should see · example output
Read: open
rustc --edition=2024 lesson.rs -o lesson
./lesson3. Explain the result
label borrows task and returns one of two string literals, which are valid for the program’s lifetime. It does not return ownership of title or modify done. Use a struct when the relationship between fields matters to your program.
YOUR TURN
A small check before you continue
Change done to true. What is the printed label?
Show a suggested answer
Read: closed. The method chooses the other branch.
Sources and scope
Documentation and examples reviewed 2026-10-18. Provider screens, package versions and output wording can differ. Examples show expected outcomes; they are not a claim that OpenViST connected to your server or verified your setup.
