Skip to content

Come Back Later: Borrowing and State

The Course
•
45 min study

Come back to this page a few days after finishing the queue. Recalling an idea after you have started to forget it is what makes it stick, so the struggle is the point. Try each task with the hints closed and without looking back at earlier lessons. If you get stuck for more than a few minutes, open the first hint, not the solution.

The four tasks revisit the ideas the queue depends on most, and the ones the advanced course builds on: a function that returns a borrowed view tied to one of its inputs (Day 2), a map that refuses to overwrite and a report built from an iterator (Day 4), a &mut self transition that names its failure and leaves state alone when it refuses (Days 1 and 5), and a trait-bounded report written to any impl Write (Days 3 and 6). After each solution, there is one change to try. Predict its effect before you run it.

Return a borrowed view

A function that returns a reference has to say which input the reference comes from. When there are two reference parameters, Rust cannot guess, and you write the relationship with a named lifetime. Getting it right lets the result outlive any input it does not borrow from.

Exercise

Your turn

Write head(row, separator) that returns the trimmed field before the first separator, as a slice of row, or None when the separator is missing. Create the separator String inside an inner block, call head there, and print the result after the block has ended: Some("Rust") for the row Rust | 7. Also check that head("Rust", "|") is None.

Your working space Rust
fn main() {
    let row = String::from("Rust | 7");
    // Create the separator inside a block and print the view afterward.
    println!("{row}");
}
Hint 1: the idea

The slice borrows from the row. The separator is only read during the call, so its lifetime is independent of the result.

Hint 2: a first step

Ask which input the returned slice points into. Give that parameter and the reference inside the returned Option the same named lifetime, and decide whether the other parameter needs one at all.

Worked solution
Run the solution Rust
fn head<'a>(row: &'a str, separator: &str) -> Option<&'a str> {
    row.split_once(separator).map(|(head, _)| head.trim())
}

fn main() {
    let row = String::from("Rust | 7");
    let title;
    {
        let separator = String::from("|");
        title = head(&row, &separator);
    }
    assert_eq!(head("Rust", "|"), None);
    println!("{title:?}");
}
Text
Some("Rust")

The annotation ties the view to row, the input that supplies its bytes, and says nothing about separator, so the separator can be dropped at the end of the block while title lives on. Change to try: give separator the same 'a lifetime. Predict the result before you run it. The compiler now requires the separator to live as long as title, and the program fails with separator does not live long enough.

Preserve the first entry

A map with a keep-the-first rule protects data at the moment it is written. A report then reads whatever survived, in key order, without sorting. Both halves matter: the queue's duplicate check is this pattern.

Exercise

Your turn

Load the three rows into an ordered map that keeps the first title for each ID. Assert that ID 7 still holds Rust. Then print the titles that start with R, in ID order and joined by commas: Reading, Rust.

Your working space Rust
fn main() {
    let rows = [(7, "Rust"), (3, "Reading"), (7, "Replacement")];
    println!("{rows:?}");
}
Hint 1: the idea

Preserve the first value at insertion time. Then derive the report from the values that survived.

Hint 2: a first step

Look for the entry API method that stores a value only when the key is vacant. For the report, start from the map's values, which already come in key order.

Worked solution
Run the solution Rust
use std::collections::BTreeMap;

fn main() {
    let rows = [(7, "Rust"), (3, "Reading"), (7, "Replacement")];
    let mut titles = BTreeMap::new();
    for (id, title) in rows {
        titles.entry(id).or_insert(title);
    }
    let selected: Vec<&str> = titles.values().copied()
        .filter(|title| title.starts_with('R'))
        .collect();
    assert_eq!(titles.get(&7), Some(&"Rust"));
    println!("{}", selected.join(", "));
}
Text
Reading, Rust

values() yields references to the stored values, which are themselves &str, so copied() turns each &&str into a plain &str before filtering. The filter keeps the existing key order, which is why Reading (ID 3) comes before Rust (ID 7). Change to try: replace or_insert with titles.insert(id, title);. Predict both the assertion and the report. The assertion fails, because ID 7 now holds Replacement.

Refuse a transition without changing state

A method that takes &mut self can change a record, so when it refuses, the refusal must leave the record exactly as it was. Checking only the returned error does not prove that; the check has to read the stored state as well.

Exercise

Your turn

Add an error enum and a finish(&mut self) method to Book. Finishing a Reading book sets it to Finished and returns Ok(()). Finishing a Queued book returns a NotStarted error, and finishing a Finished book returns AlreadyFinished; both leave the status unchanged. For each of the three cases, assert the returned value and the stored status, then print Transition checks passed.

Your working space Rust
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Status {
    Queued,
    Reading,
    Finished,
}

struct Book {
    status: Status,
}

fn main() {
    let queued = Book { status: Status::Queued };
    println!("{:?}", queued.status);
}
Hint 1: the idea

Decide from the current status alone. Only the one allowed case may assign to the field; the two refusals return before anything is written.

Hint 2: a first step

Write the error enum first, with the derives assert_eq! needs to compare and print it. Then start the method with a match on self.status that has one arm per variant.

Worked solution
Run the solution Rust
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Status {
    Queued,
    Reading,
    Finished,
}

#[derive(Debug, PartialEq, Eq)]
enum FinishError {
    NotStarted,
    AlreadyFinished,
}

struct Book {
    status: Status,
}

impl Book {
    fn finish(&mut self) -> Result<(), FinishError> {
        match self.status {
            Status::Queued => Err(FinishError::NotStarted),
            Status::Reading => {
                self.status = Status::Finished;
                Ok(())
            }
            Status::Finished => Err(FinishError::AlreadyFinished),
        }
    }
}

fn main() {
    let mut queued = Book { status: Status::Queued };
    assert_eq!(queued.finish(), Err(FinishError::NotStarted));
    assert_eq!(queued.status, Status::Queued);

    let mut reading = Book { status: Status::Reading };
    assert_eq!(reading.finish(), Ok(()));
    assert_eq!(reading.status, Status::Finished);
    assert_eq!(reading.finish(), Err(FinishError::AlreadyFinished));
    assert_eq!(reading.status, Status::Finished);
    println!("Transition checks passed");
}
Text
Transition checks passed

Status derives Copy, so match self.status reads a copy and the arms can still assign to self.status. The method's return type says it can fail, and the error says why, so a caller can word each case differently, as the queue does. Change to try: in the Queued arm, set self.status = Status::Finished; before returning the error. Predict which assertion fails. The result assertion still passes, because the error is right; the next one fails with left: Finished and right: Queued. That is the bug a check of the result alone would miss.

Write a report to any destination

A trait bound lets one function accept every type that can describe itself, and an impl Write parameter lets the same function write to stdout in the program and to a Vec<u8> in a check. Together they make the output testable without capturing the terminal.

Exercise

Your turn

Define a trait Describe with one method, describe(&self) -> String, and implement it for both structs: a book describes itself as Rust (300 pages) and an article as Lifetimes (8 min read). Write one generic report function that takes a slice of any Describe type and an impl Write, writes - and the description for each item, then Items: N. Check the two books by writing into a Vec<u8> and comparing the exact text, then report the article to stdout. The program should print:

Text
- Lifetimes (8 min read)
Items: 1
Your working space Rust
struct Book {
    title: String,
    pages: u32,
}

struct Article {
    title: String,
    minutes: u32,
}

fn main() {
    let books = [
        Book { title: String::from("Rust"), pages: 300 },
        Book { title: String::from("Traits"), pages: 120 },
    ];
    let articles = [Article { title: String::from("Lifetimes"), minutes: 8 }];
    println!("{} books, {} article", books.len(), articles.len());
}
Hint 1: the idea

The trait is the one thing report knows about its items, so report needs a bound on its type parameter. writeln! works on any writer and returns an io::Result, which ? can pass up.

Hint 2: a first step

Write the trait and the two impl ... for blocks first, and test them with a plain println! of each description. Then write the signature of report: one type parameter with a bound, and a return type that can carry a write error.

Worked solution
Run the solution Rust
use std::io::{self, Write};

trait Describe {
    fn describe(&self) -> String;
}

struct Book {
    title: String,
    pages: u32,
}

struct Article {
    title: String,
    minutes: u32,
}

impl Describe for Book {
    fn describe(&self) -> String {
        format!("{} ({} pages)", self.title, self.pages)
    }
}

impl Describe for Article {
    fn describe(&self) -> String {
        format!("{} ({} min read)", self.title, self.minutes)
    }
}

fn report<T: Describe>(items: &[T], mut output: impl Write) -> io::Result<()> {
    for item in items {
        writeln!(output, "- {}", item.describe())?;
    }
    writeln!(output, "Items: {}", items.len())
}

fn main() -> io::Result<()> {
    let books = [
        Book { title: String::from("Rust"), pages: 300 },
        Book { title: String::from("Traits"), pages: 120 },
    ];
    let mut buffer = Vec::new();
    report(&books, &mut buffer)?;
    assert_eq!(String::from_utf8(buffer).unwrap(), "- Rust (300 pages)\n- Traits (120 pages)\nItems: 2\n");

    let articles = [Article { title: String::from("Lifetimes"), minutes: 8 }];
    report(&articles, io::stdout().lock())
}
Text
- Lifetimes (8 min read)
Items: 1

report(&books, &mut buffer) lends the vector, so buffer still holds the bytes afterward; passing buffer itself would move it into report and lose them. The compiler builds one report for Book and one for Article, and the bound is what makes item.describe() callable inside it. Change to try: add report(&[1, 2], &mut Vec::new())?; to main. Predict where the error points. It is error[E0277]: the trait bound {integer}: Describe is not satisfied, at the call, with a help line listing Book and Article as the types that do implement Describe.

Was this article helpful?

Your response is saved on this device.