Rust · Chapter 11 of 26

Traits

By the end of this chapter you can define a trait and implement it for your own types, give it default methods, make your types print with {} through Display, derive PartialEq, PartialOrd and Default, convert between types with From and Into, write a function that takes any type with a trait (impl Trait), keep different types in one list behind a trait object (dyn Trait), and say what the compiler does with each. 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

Chapter 8 priced milk with a match on the kind: one arm for cow, one for buffalo. Neha now has a third rule to add: from November, societies in Kheda pay a winter premium on buffalo milk, and the plant wants to try a flat rate at two societies. With a match, every function that prices milk needs a new arm, in every file, and a function that should work for "any rule" has to know every rule there is.

The slip has the same problem from the other side. Chapter 7's structs print with {:?}, which is for programmers: quotes, braces and field names. The box's printer needs println!("{slip}") to print the three lines a farmer reads, and today that does not compile, because Rust does not know how a Slip should look. And every function that turns one of doodh's pourings into a slip writes the same eight field copies by hand.

What is missing is a way to say what a type can do, separately from what it is, so that code can be written for anything that can do it.

What you build: 4 tasks

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

  1. Task 1

    rule.rs: cow and buffalo rules behind one trait

    rule.rs gives the trait PriceRule with three methods, per_litre(&self, fat: u32, snf: u32) -> u64, accepts(&self, fat: u32, snf: u32) -> bool and amount(&self, ml: u32, fat: u32, snf: u32) -> u64, and two unit-like structs, CowRule and BuffaloRule, that implement it. Write the bodies.

    per_litre: for CowRule fat times 32 plus snf times 20; for BuffaloRule fat times 40 plus snf times 16. accepts: true when fat and snf are both at least the minimums, 30 and 80 for CowRule, 50 and 85 for BuffaloRule. amount is the trait's default method, written once in the trait for every rule: 0 when the rule does not accept the milk, otherwise ml times per_litre, divided by 1000 and rounded to the nearest paisa.

    The Check expects CowRule.per_litre(40, 85) 2980 and (42, 86) 3064; BuffaloRule.per_litre(71, 90) 4280 and (50, 85) 3360; CowRule.accepts (30, 80) true, (29, 85) false, (40, 79) false; BuffaloRule.accepts (50, 85) true, (49, 90) false, (60, 84) false; CowRule.amount(4880, 42, 86) 14952, (5000, 29, 85) 0 and (0, 40, 85) 0; BuffaloRule.amount(8970, 72, 87) 38320 and (9000, 72, 84) 0. It also implements PriceRule for a rule of its own, writing only per_litre (always 3000) and accepts (fat above 0), and expects your default amount to give 7500 for (2500, 40, 85) and 0 for (2500, 0, 85).

  2. Task 2

    slip.rs: a slip that prints itself

    slip.rs gives the struct Slip with society and farmer (String), kind (doodh's Kind), ml, fat and snf (u32), accepted (bool) and paise (u64). Implement Display for it, so that a slip printed with {} gives exactly three lines, with no line break after the last:

    S033 F11532 cow

    9.250 L, fat 3.4%, SNF 8.3%

    Amount: ₹254.19

    Line 1 is the society, the farmer and the kind (doodh's Kind prints as cow or buffalo with {}). Line 2 is the litres with three digits after the point, from ml, then fat and SNF with one digit after the point, from tenths (34 is 3.4). Line 3 is the amount with two digits of paise after the point; when accepted is false, line 3 is just Rejected. Use whole numbers with / and %, no f64.

    The Check prints a slip for S033 F11532 cow, 9250 ml, fat 34, snf 83, accepted, 25419 paise (the lines above); S002 F10193 buffalo, 2710 ml, fat 81, snf 81, not accepted (2.710 L, fat 8.1%, SNF 8.1% and Rejected); S018 F10880 buffalo, 16770 ml, fat 85, snf 90, 80898 paise (16.770 L, fat 8.5%, SNF 9.0% and Amount: ₹808.98); and S014 F10660 cow, 5 ml, fat 40, snf 85, 5 paise (0.005 L, fat 4.0%, SNF 8.5% and Amount: ₹0.05).

  3. Task 3

    from.rs: a slip from one of doodh's pourings

    Implement From<&doodh::Collection> for Slip (Task 2's struct) in from.rs, so the box can write Slip::from(&pouring) or let slip: Slip = (&pouring).into(). Each field of the Slip comes from the pouring's field of the same name, and accepted is true when the pouring's status is Status::Accepted.

    For Tuesday's first pouring (id 1: S033, F11532, cow, 9250 ml, fat 34, snf 83, accepted, 25419 paise) every field matches and accepted is true; for id 12 (S002, F10193, buffalo, 2710 ml, fat 81, snf 81, rejected, 0 paise) accepted is false. The Check makes Slips from both of those and from every pouring of S001, with from and with into, and compares every field.

  4. Task 4 · interview question

    Interview: pick.rs, impl Trait or dyn Trait

    Write three functions in pick.rs with Task 1's PriceRule (so do Task 1 first). day_total(rule: &impl PriceRule, cans: &[(u32, u32, u32)]) -> u64 returns the total of rule.amount for each (ml, fat, snf) can. rule_for(kind: Kind) -> Box<dyn PriceRule> returns CowRule for Kind::Cow and BuffaloRule for Kind::Buffalo, in a Box. mixed_total(cans: &[(Kind, u32, u32, u32)]) -> u64 returns the total of cans of both kinds, each priced by the rule for its own kind.

    The Check expects day_total(&CowRule, &[(4880, 42, 86), (5000, 29, 85)]) 14952, day_total(&BuffaloRule, &[(8970, 72, 87), (10000, 71, 90)]) 81120, 7500 for a rule of its own at 3000 paise a litre, and 0 for an empty list; rule_for(Kind::Buffalo).per_litre(71, 90) 4280, rule_for(Kind::Cow).per_litre(71, 90) 4072 and rule_for(Kind::Cow).accepts(29, 85) false; mixed_total of (Kind::Cow, 4880, 42, 86) and (Kind::Buffalo, 8970, 72, 87) 53272, and of all of Tuesday's 10,164 pourings 293257264 paise (₹29,32,572.64).

    Farhan will ask: impl Trait or dyn Trait, what does the compiler do with each? Why can rule_for not return impl PriceRule?

What you will learn

  • trait: a set of methods a type can promise to have; impl Trait for Type.
  • Default methods: written once in the trait, used by every type unless it writes its own.
  • Display: impl fmt::Display, so {} and to_string() work.
  • Derived traits: Debug, PartialEq, PartialOrd and Default.
  • From and Into: converting one type into another.
  • impl Trait and dyn Trait: a function for any type with a trait, and different types in one list.
  • The orphan rule: which traits you may implement for which types.

More in Traits and data

Build "Traits" 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.