Every add command in the queue crosses an ownership boundary. The title starts as part of an input line that lives for one loop iteration, and it ends as part of a Book that lives as long as the queue. Somewhere in between, a borrowed &str has to become an owned String. Where that happens decides two things: whether the program compiles, and whether a rejected command costs an allocation. This lesson traces that path through the real files.
Trace the path
Open the playground below and find each step in the files as you read.
- In
app.rs,input.lines()produces aStringcalledline. It is dropped at the end of the loop iteration. parse(&line)incommand.rsreturns aCommand<'_>. The'_says the command borrows fromline.Command::Add { id, title }holds a validatedBookIdand atitle: &strthat points into the line's bytes, already trimmed. Nothing has been copied yet.app.rsmatchesCommand::Add { id, title }and callsqueue.add(id, title), still within the same iteration, whilelineis alive.- In
queue.rs,addtrims again, rejects an empty title, then callsself.books.entry(id). Only theEntry::Vacantarm callsString::from(title), moves the newStringinto aBook, and stores it in the map. - The iteration ends and
lineis dropped. The map'sBookowns its own copy of the title, so nothing points at the dropped line.
BookId derives Ord so the BTreeMap can order it. For this one-field wrapper, the derived ordering compares the wrapped u32, so the report is in numeric ID order. The Copy derive lets app.rs pass id to queue.add and still format it afterward with id.get(). Without Copy, the call would move the ID, and the id.get() after it would fail with error[E0382]: use of moved value: id. The private field still prevents creating a zero ID outside the queue module: the only way to get a BookId is BookId::new, which returns None for zero.
Added #5
Line 2: ID is already in use
Reading queue
#5 [pending] Rust Types
Pending: 1 | Finished: 0The first line has extra spaces between the ID and the title and after the title; the parser's trim removes them, but the space inside Rust Types survives. The second line reaches Entry::Occupied and returns DuplicateId before any String is created. The report borrows the stored title from the surviving Book through book.title().
Why the map cannot keep the slice
You might ask why the queue copies at all, since the parser already has a perfectly good &str. The compiler answers. Here is a stripped-down loop that stores the borrowed slices directly:
use std::collections::BTreeMap;
fn main() {
let input = vec![String::from("7 Rust"), String::from("3 Types")];
let mut titles = BTreeMap::new();
for line in input {
if let Some((id, title)) = line.split_once(' ') {
titles.insert(id, title);
}
}
println!("{titles:?}");
}It fails with error[E0597]: line does not live long enough, and the compiler points at the end of the loop body, where line is dropped while the map still borrows it. A map that outlives the loop needs values that do not depend on the loop. Converting at the point of storage fixes it:
use std::collections::{BTreeMap, btree_map::Entry};
fn main() {
let input = vec![String::from("7 Rust"), String::from("3 Types"), String::from("7 Again")];
let mut titles: BTreeMap<u32, String> = BTreeMap::new();
let mut allocations = 0;
for line in input {
if let Some((id, title)) = line.split_once(' ') {
let id: u32 = id.parse().expect("fixture IDs are numbers");
if let Entry::Vacant(slot) = titles.entry(id) {
slot.insert(String::from(title));
allocations += 1;
}
}
}
println!("{titles:?}");
println!("Titles copied: {allocations}");
}{3: "Types", 7: "Rust"}
Titles copied: 2Three lines arrived, but only two titles were copied: the duplicate 7 Again was rejected while it was still a borrowed slice. That is the queue's design in miniature: borrow while deciding, own once you keep.
Copy at the point of storage
Let parsers and validators borrow. Convert to an owned type at the one place where data is kept beyond the current iteration or request. That keeps lifetimes short and simple, and it means rejected input never allocates.
Practice
Trace the ownership change
For the two add commands in the queue run above, explain when the title is a slice, when the code allocates a String, and what the occupied entry does. Then write down why the final report can still borrow the first title after both input lines are gone.
Hint 1: the idea
Separate the lifetime of the input line from the lifetime of a Book in the map. Each line lives for one iteration; the map lives for the whole run.
Hint 2: a first step
Find String::from(title) in queue.rs and identify which entry variant can reach it.
Worked solution
Both commands start as a Command::Add whose title is a slice of its own line. The first reaches Entry::Vacant: String::from(title) allocates a new String, which moves into a Book owned by the map. The second reaches Entry::Occupied and returns DuplicateId before a Book or a String is constructed, so its slice simply goes away with its line. The final report borrows from the String inside the surviving Book, which belongs to the queue and does not depend on any input line. The next lesson runs the checks that prove these rules hold.
Completion is saved in this browser only. It does not measure mastery.