Rust · Chapter 9 of 26
Result and errors
By the end of this chapter you can turn text into numbers with parse, handle a failure with Result and match, pass an error up to the caller with ?, turn one error into another with map_err and a missing value into an error with ok_or, walk a text line by line, and explain why the collection box never calls unwrap on what the scale and the analyser send. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: The language
- 4 tasks
- Rust
- In the all labs plan
The first 2 chapters of Rust are free. This one comes with the all labs plan.
Why you need this
Chapter 8's classifier sorts Karamsad's 211 morning lines into cans and broken lines, but it keeps the numbers as text: "4.88", "4.2", "8.6". Neha cannot pay a farmer for "4.88"; she needs 4,880 millilitres and 42 tenths of fat, as whole numbers. Turning text into a number can fail: the analyser sends ERR, a field arrives empty, a scale puts a comma where the point should be.
The Rust you know so far has two answers, and neither fits. Option can say "no number here", but not why, and when four of 211 lines are skipped Neha needs to know which field of which line, to fix the slip by hand. A panic says why, but it stops the program, and a box that stops is the morning of 12 October. The box needs a third answer: a value that is either the number or the reason it could not be read, which the code must look at before it can use the number, and which can travel up to whoever decides what to do: print a "skipped" slip, count the line as broken, and carry on with the next can.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
litres.rs: litres as text to whole millilitres
Write to_ml(text: &str) -> Result<u32, String>. It turns litres written as text into whole millilitres, rounded to the nearest millilitre, or returns an error. Spaces around the text do not matter. Parse the text as an f64.
Errors, exactly: an empty text, or one of only spaces, is Err("litres are empty"); text that is not a number is Err("litres are not a number: " followed by the text without its spaces), such as litres are not a number: 4,88; a number below zero is Err("litres cannot be negative: " followed by the text), such as litres cannot be negative: -1.5.
The Check expects Ok(4880) for 4.88, Ok(16770) for 16.77, Ok(5000) for 5, Ok(500) for 0.5, Ok(9160) for " 9.16 ", Ok(8110) for 8.11 and Ok(0) for 0; and the errors for the empty text, three spaces, 4,88, four, ERR and -1.5. 8.11 times 1000 is 8109.999999999999 as an f64, so convert only after rounding.
- Task 2
line.rs: a whole analyser line, or why not
line.rs gives the enum Kind (Cow, Buffalo) and the struct Can with time and farmer (String), kind (Kind), ml, fat and snf (u32). Write parse_line(line: &str) -> Result<Can, String> for one analyser line, time,farmer,kind,litres,fat,snf. ml is the litres times 1000, and fat and snf are tenths of a percent (4.2 is 42), each rounded to the nearest whole number. 06:02:07,F10122,cow,4.88,4.2,8.6 gives Ok(Can { time 06:02:07, farmer F10122, kind Kind::Cow, ml 4880, fat 42, snf 86 }).
Errors, checked in this order: an empty line or one of only spaces is Err("empty line"); a line that ends before a field is Err("missing farmer"), Err("missing kind"), Err("missing litres"), Err("missing fat") or Err("missing snf"), for the first field that is missing; a kind other than cow or buffalo is Err("bad kind: goat") with the kind's text; litres, fat or snf that is not a number is Err("bad litres: \"six\""), Err("bad fat: \"ERR\"") or Err("bad snf: \"8.6x\""), the field's name and its text in double quotes as {:?} prints it (an empty litres field gives bad litres: ""). Fields after the sixth are ignored. Hand each error back with ?, using ok_or for a missing field and map_err for a number that will not parse.
The Check tries good lines of both kinds (06:03:14,F10122,buffalo,3.08,8.3,9.4 is ml 3080, fat 83, snf 94, and a buffalo can of 8.11 litres is ml 8110); the empty line and two spaces; lines that stop after the time, after the farmer (07:55:03,F1013), after the kind, after the litres and after the fat; the kind goat; litres that are empty and six; fat ERR; and snf 8.6x and empty.
- Task 3
shift.rs: a shift's totals, broken lines and all
shift.rs gives the struct Totals with cans (u32), ml (u64), broken (u32) and first_broken (Option<u32>). Write totals(text: &str) -> Totals: go through the text's lines with a for loop over text.lines(), give each line to parse_line from Task 2, and count as you go without stopping. cans counts the lines that parsed and ml adds up their ml; broken counts the lines that did not, and first_broken is Some of the first broken line's number, counting from 1, or None when there is none.
For 06:02:07,F10122,cow,4.88,4.2,8.6, an empty line, 06:03:14,F10122,buffalo,3.08,8.3,9.4 and 06:04:55,F10113,buffalo,3.31,ERR,ERR, it returns cans 2, ml 7960, broken 2, first_broken Some(2). The Check also tries the first and third of those lines alone (cans 2, ml 7960, broken 0, first_broken None), the empty text (0, 0, 0, None), and Karamsad's whole morning log of 211 lines: cans 207, ml 1935880, broken 4, first_broken Some(18). This task needs parse_line, so do Task 2 first.
- Task 4 · interview question
Interview: tenths.rs, unwrap or ?
tenths.rs has two functions Lakhan wrote to read fat and SNF, tenths(text: &str) -> Result<u32, String> and fat_and_snf(fat: &str, snf: &str) -> Result<(u32, u32), String>. Both return a Result, yet fat_and_snf("4.2", "ERR") still panics, because they unwrap. Fix them, keeping their names and types, so they never panic and hand every error back.
tenths turns text into tenths of a percent, rounded, ignoring spaces around it: tenths("4.2") is Ok(42) and tenths(" 8.6 ") is Ok(86). Text that is not a number is Err("not a number: ") followed by the text as tenths was given it, in double quotes: tenths("ERR") is Err("not a number: \"ERR\"") and tenths("") is Err("not a number: \"\"").
fat_and_snf returns both: fat_and_snf("4.2", "8.6") is Ok((42, 86)). Its errors say which field: fat_and_snf("ERR", "8.6") is Err("fat: not a number: \"ERR\"") and fat_and_snf("4.2", "ERR") is Err("snf: not a number: \"ERR\""). Use ? to hand errors back, and map_err to change an error first. The Check tries these and reads tenths.rs: it must have no unwrap and no expect.
Farhan will ask: unwrap or ?, what does each do at a village counter at 7 am?
What you will learn
- panic and Result: a bug stops the program; an expected failure is a value, Ok(v) or Err(e).
- parse: text to u32 or f64, and the errors it gives.
- match on Ok and Err: handle both cases.
- The ? operator: hand an error to the caller in one character.
- map_err and ok_or: change an error, and turn a missing value into one.
- expect and main returning Result: and why the box never unwraps.
- for line in text.lines(): walk a text, counting as you go.
More in The language
Build "Result and errors" yourself
DoodhSetu runs the milk collection boxes of 120 village societies around Anand. The old box program crashed on an empty line, and you rebuild it in Rust. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of Rust are free. This one comes with the all labs plan.