Rust · Chapter 12 of 26
Generics
By the end of this chapter you can write one function, one struct or one impl block that works for many types, say what each type must be able to do with a trait bound, read the compiler's errors when a bound is missing, explain what the compiler builds from generic code, and choose between generics and a trait object. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Traits and data
- 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
Neha's payout reports keep asking the same questions of different data. How many cans had fat above 6.0%? How many pourings earned more than ₹100? Which society id comes last? How many pourings were cow milk and how many buffalo, how many came from each of the 120 societies, how many from each of the 4,773 farmers who poured on Tuesday? And what did it all earn: the 10,164 pourings from the plant's data, and the slips the box printed, which are a different type?
With the Rust you know so far, each of those is a new function, because every function names its types. Here are two that count values above a limit, one for fat (u32) and one for paise (u64):
fn count_above_u32(items: &[u32], limit: u32) -> usize {
let mut n = 0;
for &x in items {
if x > limit {
n += 1;
}
}
n
}
fn count_above_u64(items: &[u64], limit: u64) -> usize {
let mut n = 0;
for &x in items {
if x > limit {
n += 1;
}
}
n
}
2
2
The two bodies are the same, letter for letter; only the type changed. A third for litres (f64) and a fourth for times (&str) would be the same again, and a fix in one would have to be copied into all four. A counter by kind of milk, by society and by farmer would be three copies of the same HashMap code. Generics let you write each of them once.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
largest.rs: the largest value of any slice
Write pub fn largest<T: PartialOrd + Copy>(items: &[T]) -> Option<T> in largest.rs. It returns the largest value in the slice, or None when the slice is empty. The starter's T has no bounds yet: add PartialOrd (for comparing) and Copy (for handing a value back out of the slice).
The Check calls largest(&[91_u32, 86, 94, 88]) and expects Some(94), largest(&[6.4, 7.1, 5.8]) Some(7.1), largest(&["S014", "S118", "S001"]) Some("S118"), largest(&[5_u64, 5]) Some(5), largest(&[3_i32]) Some(3) and largest::<u64>(&[]) None. It also gives it every pouring's ml from doodh::collections(), in the day's order and reversed, and expects Some(22400) both times.
Because the Check calls it with f64, the bound must be PartialOrd, not Ord.
- Task 2
tally.rs: a Tally that counts any kind of key
Tally<K> in tally.rs has one field, counts: HashMap<K, u32>. Add the bounds K: Eq + Hash to its impl block (Hash comes from std::hash) and write its five pub methods: new() -> Self, an empty tally; add(&mut self, key: K), which counts key once more; count(&self, key: &K) -> u32, how many times key was added (0 for a key never added, without panicking); keys(&self) -> usize, how many different keys were added; and total(&self) -> u32, how many adds there were in all.
The Check makes a Tally<&str> and adds "S001", "S001" and "S014": count(&"S001") must be 2, count(&"S014") 1, count(&"S099") 0, keys() 2 and total() 3. A new Tally<doodh::Shift> must give keys() 0, total() 0 and count 0. A Tally<doodh::Kind> of every pouring's kind must count 4384 Cow and 5780 Buffalo, with keys() 2 and total() 10164. A Tally<String> of the farmer ids of S001's pourings must count each farmer's pourings, and keys() must be the number of different farmers.
- Task 3
paise.rs: one total for anything that earns paise
The trait HasPaise in paise.rs has one method, fn paise(&self) -> u64. Implement it for doodh::Collection (a pouring is worth its paise field) and for Slip { ml: u32, per_litre: u64 } (ml times per_litre, divided by 1000, to the nearest paisa: add 500 before dividing). Then write pub fn total<T: HasPaise>(items: &[T]) -> u64, the sum of every item's paise(); the starter's T has no bound yet.
The Check expects Slip { ml: 5250, per_litre: 4016 } to be worth 21084 and Slip { ml: 3310, per_litre: 4632 } 15332 (15331.92 rounded), total of those two slips 36416, total(&doodh::collections()) 293257264, total of S001's pourings 12415897, and total of an empty slice 0. It also calls total on a type of its own that implements HasPaise, so total must use paise() and nothing else of its items. Keep every sum a u64: the day's total does not fit in a u32.
- Task 4 · interview question
Interview: bonus.rs, two kinds of bonus in one list
bonus.rs has the trait Bonus (fn extra(&self, c: &Collection) -> u64) and two rules that implement it: FatBonus { min_fat, paise } pays paise for an accepted can with fat of min_fat or more, and MorningBonus { paise } pays paise for an accepted morning can. Write two functions:
pub fn todays_rules() -> Vec<Box<dyn Bonus>> returns exactly two rules, in this order: FatBonus { min_fat: 70, paise: 100 }, then MorningBonus { paise: 50 }.
pub fn bonus(rules: &[Box<dyn Bonus>], c: &Collection) -> u64 returns the sum of every rule's extra for the can, for any list of rules.
The Check expects, with todays_rules(): an accepted morning can with fat 72 earns 150, an accepted evening can with fat 72 earns 100 (the first rule 100, the second 0), an accepted morning can with fat 42 earns 50 (the first rule 0, the second 50), an accepted can with fat exactly 70 gets 100 from the first rule, an accepted evening can with fat 42 earns 0 and a rejected morning can with fat 72 earns 0. It sums the bonus over all of S001's pourings and compares it with its own sum, and calls bonus on a list of two rules of its own (7 paise each: 14) and on an empty list (0).
Farhan will ask: why can a generic Vec<T> not hold both rules, what does Box<dyn Bonus> cost instead, and when would you still choose generics?
What you will learn
- Type parameters: fn name<T>(..), one function for many types.
- Trait bounds: T: PartialOrd + Copy says what T must be able to do.
- where clauses: the same bounds, written after the signature.
- Generic structs and impl blocks: struct Window<T>, impl<T: PartialOrd> Window<T>.
- Option and Result are generic enums you have used since chapter 8.
- Monomorphization: the compiler writes one copy of the code per type.
- Generics or a trait object: when Box<dyn Trait> is the better tool.
More in Traits and data
Build "Generics" 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.