Skip to content

Trace a Request from Borrow to Owned Data

The Course
•
32 min study

Each time the loop in main.rs reads a line, it gets a new String. At the end of that loop iteration the String is dropped and its memory is freed. Yet the report at the end still prints every accepted topic. This lesson follows one request through add_line in planner.rs to find the exact moment where borrowed text becomes text the planner owns, which is what makes that possible.

Open planner.rs and follow the input Borrowing , 20, with spaces around both parts, through these steps:

  1. main.rs calls planner.add_line(&line). The method borrows the line as a &str; main.rs still owns the String.
  2. split_once(',') returns an Option. Its Some case holds a tuple, a pair of values written in parentheses: here two text slices, " Borrowing " and " 20". Both still point into the original line. let (topic, minutes) = ... gives each half a name. With no comma, the None arm runs return Err("use topic,minutes") and leaves the method early.
  3. topic.trim() makes a narrower slice, "Borrowing", still pointing into the line. An empty result is rejected with enter a topic.
  4. minutes.trim().parse::<u32>() turns "20" into the number 20 and checks the range, as on Day 5.
  5. After every check has passed, String::from(topic) copies the text into a new String, which moves into a Session, which moves into the private vector.
Trace a valid and invalid request Rust
mod planner; use planner::Planner; use std::io::{self, BufRead}; fn main() { let mut planner = Planner::new(); for (index, line) in io::stdin().lock().lines().enumerate() { let number = index + 1; match line { Ok(line) => { if !line.trim().is_empty() { match planner.add_line(&line) { Ok(()) => {} Err(message) => println!("Line {number}: {message}"), } } } Err(_) => { eprintln!("Could not read line {number}"); break; } } } println!("Study plan"); for session in planner.sessions() { println!("{}: {} min", session.topic, session.minutes); } println!( "Sessions: {} | Minutes: {}", planner.sessions().len(), planner.total_minutes() ); } pub struct Session { pub topic: String, pub minutes: u32, } pub struct Planner { sessions: Vec<Session>, } impl Planner { pub fn new() -> Self { Self { sessions: Vec::new() } } pub fn add_line(&mut self, line: &str) -> Result<(), &'static str> { let (topic, minutes) = match line.split_once(',') { Some(pair) => pair, None => return Err("use topic,minutes"), }; let topic = topic.trim(); if topic.is_empty() { return Err("enter a topic"); } let minutes = match minutes.trim().parse::<u32>() { Ok(value) if value >= 1 && value <= 240 => value, Ok(_) => return Err("use 1–240 minutes"), Err(_) => return Err("enter a whole number"), }; if self.sessions.len() >= 100 { return Err("planner is full"); } self.sessions.push(Session { topic: String::from(topic), minutes, }); Ok(()) } pub fn sessions(&self) -> &[Session] { &self.sessions } pub fn total_minutes(&self) -> u32 { let mut total = 0; for session in &self.sessions { total += session.minutes; } total } } Borrowing , 20 ,15
Text
Line 2: enter a topic
Study plan
Borrowing: 20 min
Sessions: 1 | Minutes: 20

The second line, ,15, has a comma, but its topic trims to nothing, so step 3 rejects it before any number is parsed. Nothing was copied for it, because the copy happens only at step 5.

Write it: split one request

Steps 2 and 3 are the part of the parser you will write yourself in On Your Own, later today, so write them once here, on their own.

Exercise

Split and trim a request

Complete the loop so each line is split at its first comma, both halves are trimmed, and the halves are printed in brackets. A line with no comma prints the planner's message instead. The program should print:

Text
[Borrowing] [20]
Review: use topic,minutes
Your working space Rust
fn main() {
    for line in ["  Borrowing  , 20", "Review"] {
        // Split line at the first comma and print the trimmed halves.
        println!("{line}");
    }
}
Hint 1: the idea

split_once(',') returns an Option. Its Some case holds a tuple of two slices, and a pattern written like a tuple, with two names in parentheses, unpacks it.

Hint 2: a first step

Replace the println! with match line.split_once(',') and write the None arm first: it only prints. In the Some arm, the pattern needs two names for the halves.

Worked solution
Run the solution Rust
fn main() {
    for line in ["  Borrowing  , 20", "Review"] {
        match line.split_once(',') {
            Some((topic, minutes)) => {
                println!("[{}] [{}]", topic.trim(), minutes.trim());
            }
            None => println!("{line}: use topic,minutes"),
        }
    }
}
Text
[Borrowing] [20]
Review: use topic,minutes

Some((topic, minutes)) has two sets of parentheses: the outer ones belong to Some, the inner ones are the tuple pattern. planner.rs writes the same thing as let (topic, minutes) = match ... { Some(pair) => pair, None => return Err(...) };, which names the halves once and leaves the method early on None, so the rest of the method can use them without another level of match. Both forms only borrow: topic.trim() is still a view into line.

Why the copy is necessary

It might seem simpler to store the trimmed slice itself and skip the copy. The compiler will not allow it, and the reason is the whole point of Day 3. Here is the same idea in a few lines, keeping &str slices in a vector:

Rust
fn main() {
    let mut topics: Vec<&str> = Vec::new();
    for text in ["  Borrowing  , 20", "Loops,25"] {
        let line = String::from(text);
        if let Some((topic, _)) = line.split_once(',') {
            topics.push(topic.trim()); // error
        }
    }
    println!("{topics:?}");
}
Text
error[E0597]: `line` does not live long enough

Each slice points into line, and line is dropped at the end of its loop iteration. The vector would be left holding views of memory that no longer exists, so the compiler rejects the program. The note under the error says it plainly: line is dropped here while still borrowed. Copying the text into an owned String fixes it, because the vector then owns its topics outright:

Store owned copies of each topic Rust
fn main() {
    let mut topics: Vec<String> = Vec::new();
    for text in ["  Borrowing  , 20", "Loops,25"] {
        let line = String::from(text);
        if let Some((topic, _)) = line.split_once(',') {
            topics.push(String::from(topic.trim()));
        }
    }
    println!("{topics:?}");
}
Text
["Borrowing", "Loops"]

Reading without handing out control

The report needs to read the sessions, but it must not be able to add or remove them. sessions() returns &[Session], a shared slice: a read-only view of the vector's items. The report can loop over it and read each topic and minutes, but it cannot push, so add_line stays the only place where the list can grow and every session in it has passed the checks.

Borrow while checking, own when storing

Borrowed slices are cheap and are the right tool while you inspect and validate input. Make an owned copy only for the data you decide to keep, and only after it has passed every check.

Practice

Exercise

Explain the ownership boundary

Why can the report use the trimmed topic after the line that supplied it is gone? Write down the line in planner.rs where a borrow becomes owned data, and what would go wrong without it.

Hint 1: the idea

Follow the trimmed topic through the successful validation branch and into the vector.

Hint 2: a first step

Find the conversion used to create the topic field inside the Session.

Worked solution

The local topic is a text slice borrowing from the input line. String::from(topic), inside the self.sessions.push(...) call, makes an owned String with the same text. The vector owns the Session and its String, so the report can borrow them long after the input line was dropped. Without the copy, the stored topic would point into a dropped line, and the compiler would reject the program with E0597, as in the small example above.

Was this article helpful?

Your response is saved on this device.