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:
main.rscallsplanner.add_line(&line). The method borrows the line as a&str;main.rsstill owns theString.split_once(',')returns anOption. ItsSomecase 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, theNonearm runsreturn Err("use topic,minutes")and leaves the method early.topic.trim()makes a narrower slice,"Borrowing", still pointing into the line. An empty result is rejected withenter a topic.minutes.trim().parse::<u32>()turns"20"into the number 20 and checks the range, as on Day 5.- After every check has passed,
String::from(topic)copies the text into a newString, which moves into aSession, which moves into the private vector.
Line 2: enter a topic
Study plan
Borrowing: 20 min
Sessions: 1 | Minutes: 20The 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.
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:
[Borrowing] [20]
Review: use topic,minutesfn 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
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"),
}
}
}[Borrowing] [20]
Review: use topic,minutesSome((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:
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:?}");
}error[E0597]: `line` does not live long enoughEach 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:
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:?}");
}["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
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.
Completion is saved in this browser only. It does not measure mastery.