Skip to content

Follow a Borrow Through the Queue

The Course
•
24 min study

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.

  1. In app.rs, input.lines() produces a String called line. It is dropped at the end of the loop iteration.
  2. parse(&line) in command.rs returns a Command<'_>. The '_ says the command borrows from line. Command::Add { id, title } holds a validated BookId and a title: &str that points into the line's bytes, already trimmed. Nothing has been copied yet.
  3. app.rs matches Command::Add { id, title } and calls queue.add(id, title), still within the same iteration, while line is alive.
  4. In queue.rs, add trims again, rejects an empty title, then calls self.books.entry(id). Only the Entry::Vacant arm calls String::from(title), moves the new String into a Book, and stores it in the map.
  5. The iteration ends and line is dropped. The map's Book owns 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.

Trace an add, rejection and report Rust
mod app; mod command; mod queue; use std::io; fn main() -> io::Result<()> { app::run(io::stdin().lock(), io::stdout().lock()) } use crate::command::{Command, parse}; use crate::queue::Queue; use std::io::{self, BufRead, Write}; fn report(queue: &Queue, output: &mut impl Write) -> io::Result<()> { writeln!(output, "Reading queue")?; for (id, book) in queue.books() { writeln!(output, "#{} [{}] {}", id.get(), book.status().label(), book.title())?; } let (pending, finished) = queue.counts(); writeln!(output, "Pending: {pending} | Finished: {finished}") } pub fn run(input: impl BufRead, mut output: impl Write) -> io::Result<()> { let mut queue = Queue::default(); for (index, line) in input.lines().enumerate() { let line = line?; if line.trim().is_empty() { continue; } let number = index + 1; let command = match parse(&line) { Ok(command) => command, Err(error) => { writeln!(output, "Line {number}: {}", error.message())?; continue; } }; match command { Command::Add { id, title } => match queue.add(id, title) { Ok(()) => writeln!(output, "Added #{}", id.get())?, Err(error) => writeln!(output, "Line {number}: {}", error.message())?, }, Command::Finish(id) => match queue.finish(id) { Ok(()) => writeln!(output, "Finished #{}", id.get())?, Err(error) => writeln!(output, "Line {number}: {}", error.message())?, }, Command::List => report(&queue, &mut output)?, } } output.flush() } use crate::queue::BookId; #[derive(Debug, PartialEq, Eq)] pub enum Command<'a> { Add { id: BookId, title: &'a str }, Finish(BookId), List, } #[derive(Debug, PartialEq, Eq)] pub enum ParseError { UnknownCommand, InvalidId, ZeroId, MissingTitle, ExtraArguments, } impl ParseError { pub fn message(&self) -> &'static str { match self { Self::UnknownCommand => "use add, finish or list", Self::InvalidId => "use a whole-number ID", Self::ZeroId => "ID must be positive", Self::MissingTitle => "enter a title", Self::ExtraArguments => "list takes no arguments", } } } fn parse_id(text: &str) -> Result<BookId, ParseError> { let value = text.parse::<u32>().map_err(|_| ParseError::InvalidId)?; BookId::new(value).ok_or(ParseError::ZeroId) } pub fn parse(line: &str) -> Result<Command<'_>, ParseError> { let line = line.trim(); let (verb, rest) = line.split_once(char::is_whitespace).unwrap_or((line, "")); let rest = rest.trim(); match verb { "add" => { let (id, title) = rest.split_once(char::is_whitespace).unwrap_or((rest, "")); let id = parse_id(id)?; let title = title.trim(); if title.is_empty() { return Err(ParseError::MissingTitle); } Ok(Command::Add { id, title }) } "finish" => Ok(Command::Finish(parse_id(rest)?)), "list" if !rest.is_empty() => Err(ParseError::ExtraArguments), "list" => Ok(Command::List), _ => Err(ParseError::UnknownCommand), } } use std::collections::{BTreeMap, btree_map::Entry}; #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct BookId(u32); impl BookId { pub fn new(value: u32) -> Option<Self> { if value == 0 { None } else { Some(Self(value)) } } pub fn get(self) -> u32 { self.0 } } #[derive(Debug, PartialEq, Eq)] pub enum QueueError { EmptyTitle, DuplicateId, UnknownId, AlreadyFinished, } impl QueueError { pub fn message(&self) -> &'static str { match self { Self::EmptyTitle => "enter a title", Self::DuplicateId => "ID is already in use", Self::UnknownId => "book was not found", Self::AlreadyFinished => "book is already finished", } } } #[derive(Debug, PartialEq, Eq)] pub enum Status { Pending, Finished, } impl Status { pub fn label(&self) -> &'static str { match self { Self::Pending => "pending", Self::Finished => "finished", } } } pub struct Book { title: String, status: Status, } impl Book { pub fn title(&self) -> &str { &self.title } pub fn status(&self) -> &Status { &self.status } } #[derive(Default)] pub struct Queue { books: BTreeMap<BookId, Book>, } impl Queue { pub fn add(&mut self, id: BookId, title: &str) -> Result<(), QueueError> { let title = title.trim(); if title.is_empty() { return Err(QueueError::EmptyTitle); } match self.books.entry(id) { Entry::Vacant(slot) => { slot.insert(Book { title: String::from(title), status: Status::Pending }); Ok(()) } Entry::Occupied(_) => Err(QueueError::DuplicateId), } } pub fn finish(&mut self, id: BookId) -> Result<(), QueueError> { let book = self.books.get_mut(&id).ok_or(QueueError::UnknownId)?; if book.status == Status::Finished { return Err(QueueError::AlreadyFinished); } book.status = Status::Finished; Ok(()) } pub fn books(&self) -> impl Iterator<Item = (&BookId, &Book)> { self.books.iter() } pub fn counts(&self) -> (usize, usize) { let finished = self.books.values().filter(|book| book.status == Status::Finished).count(); (self.books.len() - finished, finished) } } add 5 Rust Types add 5 Alternate list
Text
Added #5
Line 2: ID is already in use
Reading queue
#5 [pending] Rust Types
Pending: 1 | Finished: 0

The 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:

Rust
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:

Store owned titles from short-lived lines Rust
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}");
}
Text
{3: "Types", 7: "Rust"}
Titles copied: 2

Three 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

Exercise

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.

Was this article helpful?

Your response is saved on this device.