Boss lesson · Unit 07
A log report
Lines of text parsed into structs, then counted, grouped and ranked
What you practise
- Lines of text parsed into structs, then counted, grouped and ranked into a report
Try a question from this lesson
Pick one
A server writes one line per request, such as "ERROR db 250": a level, the part that wrote it, and a time in ms. To find the slowest part, what comes first?
Correct answer
Turn each line into a value with typed fields
Why
As text, "250" cannot be added and "ERROR" cannot be told from a typo. Parse each line once into a struct with a level, a source and a number. Everything after that works with real types.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Split a line into words
Everything starts as text. split_whitespace walks over the words of a line, and this helper gathers them into a vector.
The pieces are &str: borrows of the original line, so nothing is copied. Only one borrowed parameter comes in, so no lifetime name is needed.
fn words(line: &str) -> Vec<&str> {
let mut out = Vec::new();
for w in line.split_whitespace() {
out.push(w);
}
out
}
let parts = words("ERROR db 250");
println!("{} {}", parts.len(), parts[1]);Concept
The record and its parser
Hidden here: Level, words and to_level.
? works on an Option too: on None the function returns None at once. .ok() turns a Result into an Option, so one ? style serves the whole function.
When a variable has the same name as a field, Entry { level, source, ms } is enough.
struct Entry {
level: Level,
source: String,
ms: i32,
}
fn parse(line: &str) -> Option<Entry> {
let p = words(line);
if p.len() != 3 {
return None;
}
let level = to_level(p[0])?;
let ms = p[2].parse::<i32>().ok()?;
let source = String::from(p[1]);
Some(Entry { level, source, ms })
}Concept
Group with a map
To add up the time per source, keep a map from source to total. entry(key).or_insert(0) finds the slot for a key, creating it at 0 the first time, and * reaches the number in the slot.
It is the counting pattern from the word counter, with += ms in place of += 1.
use std::collections::HashMap;
let entries = vec![
("db", 250), ("web", 12), ("db", 90),
];
let mut sum = HashMap::new();
for (source, ms) in entries {
*sum.entry(source).or_insert(0) += ms;
}
println!("{}", sum["db"]);9 more exercises in the app
- 1× fill the blanks
- 4× type the answer
- 1× multiple choice
- 1× order the lines
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.