Rust · Chapter 7 of 26

Structs

By the end of this chapter you can group a can's facts into one value with a struct, give it methods that read it (&self), change it (&mut self) or use it up (self), make one with an associated function such as Can::new, print and compare it with derived traits, and wrap a plain number in a type of its own so that millilitres and paise can never be mixed up. 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

A can at the counter is not one number. It is a farmer, millilitres, fat, SNF and a rate chart, and the box needs all of them together every time it prints a slip. So far every fact has been a variable of its own, and every function has taken them one by one. Neha found what that costs: a function with two whole-number parameters of the same type gives no warning when a caller passes them in the wrong order. A buffalo can at Karamsad with 7.1% fat and 9.0% SNF:

fn per_litre(fat: u32, snf: u32) -> u32 {
    fat * 40 + snf * 16
}

fn main() {
    let fat = 71;
    let snf = 90;
    println!("{}", per_litre(fat, snf));
    println!("{}", per_litre(snf, fat));
}
4280
4736

Both lines compile. The second pays 456 paise a litre too much, and on a 15.85 litre can that is over ₹72 for one pouring. Millilitres and paise are both plain numbers too, so a function that wants one will take the other just as happily. With six loose variables per can and 211 cans in Karamsad's morning, a slip printer needs a better shape for its data than a row of numbers.

What you build: 4 tasks

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

  1. Task 1

    can.rs: a can that knows what it earns

    can.rs gives two structs: Rate, with fat_paise and snf_paise (u32), and Can, with farmer (String), ml, fat and snf (u32, fat and SNF in tenths of a percent) and rate (Rate). In the impl block for Can, write three things.

    Can::new(farmer: &str, ml: u32, fat: u32, snf: u32, rate: Rate) -> Self makes a Can whose fields hold exactly what it was given, with farmer kept as a String.

    per_litre(&self) -> u64 is fat times rate.fat_paise plus snf times rate.snf_paise.

    amount(&self) -> u64 is ml times per_litre(), divided by 1000 and rounded to the nearest paisa (a half rounds up).

    The Check makes Can::new("F10113", 10160, 38, 83, cow) with the cow rate (fat_paise 32, snf_paise 20) and checks every field, then expects per_litre() 2876 and amount() 29220. A buffalo can (fat_paise 40, snf_paise 16) of 8970 ml with fat 72 and snf 87 must give 4272 and 38320 (exactly 38319.84). A cow can of 0 ml with fat 40 and snf 85 gives per_litre() 2980 and amount() 0. A cow entry of 1500000 ml with fat 41 and snf 86 gives 3032 and 4548000: ml times the rate is then more than a u32 holds, so multiply as u64.

  2. Task 2

    shift.rs: a counter for the shift

    shift.rs gives the struct ShiftCounter with society (String), cans, ml and rejected (u32). cans counts every can, accepted or rejected; ml counts only the millilitres of accepted cans. Write four things in its impl block.

    ShiftCounter::new(society: &str) -> Self starts a counter for that society, with cans, ml and rejected at 0.

    pour(&mut self, ml: u32) counts an accepted can: one more can, and its ml added.

    reject(&mut self) counts a rejected can: one more can and one more rejected, with no ml.

    summary(&self) -> String returns one line, exactly: S014: 4 cans, 1 rejected, 21600 ml accepted (the society, the cans, the rejected and the ml).

    The Check makes ShiftCounter::new("S027") and expects society "S027", 0 for the rest, and the summary S027: 0 cans, 0 rejected, 0 ml accepted. Then it makes a counter for "S014", calls pour(5250), pour(9800), reject() and pour(6550), and expects cans 4, rejected 1, ml 21600 and the summary above.

  3. Task 3

    paise.rs: paise that never mix with millilitres

    paise.rs gives the tuple struct Paise(pub u64): Paise(14542) is ₹145.42. Write four things in its impl block.

    Paise::from_rupees(rupees: u64) -> Self makes Paise from whole rupees: Paise::from_rupees(30) is Paise(3000).

    rupees(&self) -> u64 returns the whole rupees, and paise(&self) -> u64 the paise left over: 145 and 42 for Paise(14542).

    text(&self) -> String returns the amount with the rupee sign, a point and always two digits of paise: ₹145.42.

    The Check tries Paise(14542) (145, 42, ₹145.42), Paise(5) (0, 5, ₹0.05) and Paise(80898) (808, 98, ₹808.98), then Paise::from_rupees(30), which must equal Paise(3000) and print ₹30.00, and Paise::from_rupees(0), which must equal Paise(0) and print ₹0.00.

  4. Task 4 · interview question

    Interview: slip.rs, the slip printed only once

    slip.rs gives the struct Slip with farmer (String), ml (u32) and paise (u64), and Lakhan's method line(), which makes the slip's text: for Slip { farmer: "F10051", ml: 14740, paise: 42271 } it is F10051: 14740 ml, 42271 paise. The box prints every slip twice, one copy for the farmer and one for the society's book.

    Write two_copies(slip: Slip) -> (String, String): it returns the line twice, as a pair, each copy made by calling line(). Write into_farmer(self) -> String: it returns the farmer's id, giving the slip up.

    As the starter has it, line() takes the slip itself, so a second call on the same slip does not compile (E0382). Fix the cause. The Check calls two_copies on the slip above and expects that line twice, calls into_farmer() and expects F10051, and reads slip.rs: it must call line() at least twice and have no clone anywhere.

    Farhan will ask: when should a method take self, and when &self? Which of these two methods should give the slip up?

What you will learn

  • struct: one type that holds several named fields together.
  • Field init shorthand and struct update syntax: shorter ways to make one.
  • impl and methods: functions that belong to a type, taking &self, &mut self or self.
  • Associated functions and Self: Can::new(...), called on the type, not on a value.
  • derive: Debug, Clone and PartialEq, for {:?}, {:#?}, .clone() and ==.
  • Tuple structs and newtypes: struct Paise(u64), so paise and millilitres never mix.

More in The language

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