Rust · Chapter 8 of 26

Enums and match

By the end of this chapter you can define an enum, give its variants data, match on it with patterns and guards so that the compiler checks every case is handled, use Option for a value that may be missing, get the value out with match, if let and let else, and say why the old box's crash on 12 October cannot happen in code written this way. 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

On Monday 12 October the analysers at 23 societies began to send an empty line now and then, and the old box crashed on the first one at 6:47 am. Its code assumed every line had six fields. Karamsad's morning log has 211 lines, and four of them break that rule: line 18 is empty, line 59 has no litres, line 97 says ERR for fat and SNF, and line 142 is cut short after the farmer's id.

With the Rust you know so far, a function that reads a line must return something, every time. Chapter 7's struct could hold a can, but what does the function return for the empty line? A struct with "" for the farmer and 0 for the millilitres, which goes into the shift's total as a real can? There is no way yet to say "there is nothing here", and no way to say "this line is one of four kinds: a can, an empty line, an analyser error, a cut-short line". The kind of milk is the same problem in small: kept as text, "cow" and "buffalo" are fine, and so is "cwo", and nothing checks that the payout code handles both kinds.

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    rate.rs: the rate chart for a kind of milk

    rate.rs gives the enum Kind (Cow or Buffalo) and the struct Rate with fat_paise, snf_paise, min_fat and min_snf (u32). Write two functions with match on the kind.

    rate(kind: Kind) -> Rate returns the kind's chart: for Kind::Cow fat_paise 32, snf_paise 20, min_fat 30, min_snf 80; for Kind::Buffalo fat_paise 40, snf_paise 16, min_fat 50, min_snf 85.

    accepted(kind: Kind, fat: u32, snf: u32) -> bool is true when fat and snf are both at least that kind's minimums (a value equal to the minimum is accepted), and false when either is below.

    The Check calls rate for both kinds, then accepted(Kind::Cow, 30, 80) true, (Kind::Cow, 29, 86) false, (Kind::Cow, 42, 79) false, (Kind::Cow, 50, 85) true, (Kind::Buffalo, 50, 84) false, (Kind::Buffalo, 71, 90) true, (Kind::Buffalo, 42, 88) false and (Kind::Buffalo, 50, 85) true.

  2. Task 2

    reading.rs: every analyser line is a case

    reading.rs gives the enum Reading: Empty, Broken(String) with a reason, and Can { time, farmer, kind, litres, fat, snf }, where kind is a Kind (from rate.rs) and the other five are Strings. Write classify(line: &str) -> Reading for one analyser line, whose fields are split by commas: time,farmer,kind,litres,fat,snf.

    Check, in this order: an empty line or one of only spaces is Reading::Empty; fewer than 6 fields is Reading::Broken("too few fields"); more than 6 is Reading::Broken("too many fields"); fat or snf equal to ERR is Reading::Broken("analyser error"); a kind that is not exactly cow or buffalo in small letters is Reading::Broken("unknown kind: ") followed by the kind's text, such as unknown kind: goat; an empty litres field is Reading::Broken("no litres"). Anything else is Reading::Can with the six fields as text and the kind as Kind::Cow or Kind::Buffalo. Do not parse the numbers.

    The Check tries 06:14:31,F10150,cow,9.16,4.3,8.9 (a Can with time 06:14:31, farmer F10150, Kind::Cow, litres 9.16, fat 4.3, snf 8.9) and 06:01:32,F10077,buffalo,15.85,7.1,9.0 (a buffalo Can); the empty line and three spaces (Empty); 07:55:03,F1013 and a line of 5 fields (too few fields); 06:20:11,F10044,cow,6.10,4.0,8.5,B2001 (too many fields); 07:18:57,F10084,cow,9.80,ERR,ERR and a line with ERR only in snf (analyser error); the kinds goat and Cow (unknown kind: goat, unknown kind: Cow); and 06:47:18,F10128,buffalo,,7.2,9.2 (no litres).

  3. Task 3

    society.rs: a society's name, or nothing

    society.rs gives SOCIETIES, a fixed array of six (id, village) pairs: S001 Karamsad, S002 Boriavi, S014 Napad, S018 Gana, S061 Mahudha and S120 Vadol. Write two functions.

    name_of(id: &str) -> Option<&str> returns Some(village) when the id is in the array, and None when it is not.

    label(id: &str) -> String uses name_of and returns the id, a space and the village (S014 Napad), or the id followed by " (unknown society)" (S999 (unknown society)) when there is none. It must not panic.

    The Check calls both for each of the six ids, and for S999, S1 and the empty id, which must give None and S999 (unknown society), S1 (unknown society) and " (unknown society)".

  4. Task 4 · interview question

    Interview: crash.rs, what crashed the old box

    crash.rs has slip_header(line: &str) -> String, the old box's code written again in Rust just as it was. It returns the farmer and the time for a slip's top line: F10150 at 06:14:31 for 06:14:31,F10150,cow,9.16,4.3,8.9. On the empty line it panics with: called Option::unwrap() on a None value.

    Fix it so it never panics, keeping its name and types. It must return the farmer and the time as now for a line with a comma after the time and another after the farmer; skipped: empty line when there is no comma at all (the empty line); and skipped: cut short when there is a comma after the time but none after the farmer (07:55:03,F1013).

    The Check tries 06:14:31,F10150,cow,9.16,4.3,8.9, 06:47:57,F10051,cow,14.74,3.6,8.4 (F10051 at 06:47:57), 07:18:57,F10084,cow,9.80,ERR,ERR (F10084 at 07:18:57), the empty line and 07:55:03,F1013, and reads crash.rs: it must have no unwrap and no expect.

    Farhan will ask: what crashed the old box, and how does match make the compiler insist on the empty line?

What you will learn

  • enum: a type whose value is exactly one of a fixed list of variants.
  • Variants with data: Scale::Steady { grams } and Scale::Fault(String).
  • match: patterns, field bindings and guards, and the compiler's check that every case is covered (E0004).
  • Option: Some(value) or None, Rust's answer to null.
  • if let, let else and matches!: shorter ways to take one case.
  • unwrap: what it does when the value is missing, and what to use instead.

More in The language

Build "Enums and match" 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.