Skip to content

Run the Study Planner

The Course
•
24 min study

Today everything from the week comes together in one small program. The study planner reads one request per line, where each request is a topic and a number of minutes separated by a comma, such as Loops,25. It skips blank lines. For a bad request it prints the line number and the reason, then carries on with the rest of the input instead of stopping. At the end it prints the accepted sessions in the order they arrived and totals their minutes.

The program has two files with two jobs. main.rs talks to the outside world: it reads lines and prints messages and the report. planner.rs holds the rules: what a valid session is, and how sessions are stored. Neither file needs to know the other's details, which is the reason for the split you practiced on Day 6.

Predict and run

Which lines will become sessions? What total should the report show?

Predict, then run 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 } } Loops,25 Ownership,35 Review,later
Check your prediction
Text
Line 3: enter a whole number
Study plan
Loops: 25 min
Ownership: 35 min
Sessions: 2 | Minutes: 60

The error line comes first because main.rs prints problems as it reads, and prints the report only after the input ends. Replace later with 10 and predict the new total. Then clear the input and check that an empty report still makes sense: Sessions: 0 | Minutes: 0.

How main.rs reads every line

On Day 5 you read a single line. The planner needs all of them, so main.rs uses io::stdin().lock().lines(). Locking stdin gives the loop direct access to the stream, and lines() hands out one line at a time as a fresh String without its newline, wrapped in a Result because reading can fail. enumerate() pairs each line with its index, counting from 0, so index + 1 is the line number a person would use. The pair comes out as a tuple, two values in parentheses, and for (index, line) in ... gives each half its own name; the next lesson looks at tuples more closely.

lines() on a locked stdin is one of a group of reading methods called BufRead, which the standard library keeps out of the way until a file imports it. That is why main.rs starts with use std::io::{self, BufRead};. Leave BufRead out and the compiler stops with error[E0599]: no method named lines found, followed by a help line suggesting use std::io::BufRead;.

The same two methods work on ordinary text, which makes the numbering easy to see without stdin:

Number lines and skip blank ones Rust
fn main() {
    let input = "Loops,25\n\nReview,later";
    for (index, line) in input.lines().enumerate() {
        let number = index + 1;
        if line.trim().is_empty() {
            println!("Line {number}: skipped");
        } else {
            println!("Line {number}: {line}");
        }
    }
}
Text
Line 1: Loops,25
Line 2: skipped
Line 3: Review,later

A skipped line still uses up a number, so Review,later is reported as line 3, the line a person would find in their file. If the read itself fails, main.rs prints a message with eprintln!, which writes to the error stream instead of the normal output, and stops the loop with break. break ends the innermost loop at once and carries on with the code after it, here the report. That is the right reaction to a failed read: a broken input stream will not produce good lines later, but the sessions already accepted are still worth reporting.

What planner.rs promises

Planner has one field, sessions, and it is private. The only way to add a session is add_line, which returns Result<(), &'static str>: Ok(()) means "stored, nothing to report", and Err carries the message main.rs prints. Reading goes through sessions() and total_minutes(), which take &self and cannot change anything. Each Session has public topic and minutes fields, so the report can print them.

Inside add_line the checks run in a fixed order: the comma, then the topic, then the number and its range of 1 to 240, then the limit of 100 sessions. Only after every check passes does the method push. So a rejected line can never leave a half-stored session behind, the rule you proved in the Day 6 checkpoint.

Read the project from the outside in

Start with main.rs to see what the program does, then open planner.rs to see how. Most real projects reward the same order.

Practice

Exercise

Predict a whole run

Without running it, write down the full output for this input, one request per line: Loops,25, Review, a blank line, Traits,300 and Ownership ,40. Then paste the five lines into the stdin box above and compare.

Hint 1: the idea

Follow each line through the checks in add_line in order, and stop at the first one that fails.

Hint 2: a first step

Review has no comma, so split_once(',') returns None. The blank line is skipped but still counted.

Worked solution
Text
Line 2: use topic,minutes
Line 4: use 1–240 minutes
Study plan
Loops: 25 min
Ownership: 40 min
Sessions: 2 | Minutes: 65

Traits,300 parses as a number but fails the range check. Ownership ,40 is accepted because both halves are trimmed before they are checked, and the report shows the trimmed topic. The next lesson follows that topic from the borrowed input line into the stored session.

Was this article helpful?

Your response is saved on this device.