Rust · Chapter 6 of 26

Borrowing

By the end of this chapter you can lend a value to a function without giving it away, with & to read and &mut to change, follow the borrowing rules (many readers or one writer) and read their errors (E0502, E0499), take a slice of text or of an array, write functions that take &str and &[u32], use the text methods that borrow (trim, split, starts_with, contains, find), and say why a reference in Rust can never point at freed memory. 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 Tuesday morning Karamsad's analyser sent 211 lines like 06:02:07,F10122,cow,4.88,4.2,8.6, four of them broken. The box must look at each line (how many fields has it? does it say ERR?) and then still have it, to log it or show it to Lakhan. The shift report is changed by a dozen functions in turn, one line each. And Lakhan wants totals for the whole week, or just the first three days, from the same seven numbers.

With what chapter 5 taught, a function that looks at a String must take it, and then give it back in a tuple, on every call, for every one of 211 lines: clumsy, and easy to get wrong. Or it must clone the line first, and copy every byte just to read it. Neither is how anyone wants to write the box. What a function that only reads needs is to borrow the value: use it for a while, and leave the owner owning 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

    fields.rs: how many fields a line has

    Each analyser line is fields separated by commas: time,farmer,kind,litres,fat,snf. Write pub fn fields(line: &str) -> usize in fields.rs. It borrows a line, so the caller keeps it, and returns how many fields it has. Trim spaces and line breaks at both ends first. A line that is empty after trimming has 0 fields, and an empty field between two commas still counts.

    The Check calls fields with a String it lends ("06:02:07,F10122,cow,4.88,4.2,8.6", expecting 6, and the String unchanged after), then fields("06:47:18,F10128,buffalo,,7.2,9.2") 6, fields("07:18:57,F10084,cow,9.80,ERR,ERR") 6, fields("07:55:03,F1013") 2, fields("F10122") 1, fields("") 0, fields(" \n") 0, and fields(" 06:14:31,F10150,cow,9.16,4.3,8.9\n") 6.

  2. Task 2

    week.rs: a week's litres, from a slice

    Write pub fn total(litres: &[u32]) -> u32 and pub fn best(litres: &[u32]) -> u32 in week.rs. Each borrows a slice of daily litres, a whole week or any part of one. total returns their sum and best the most litres of any day; both return 0 for an empty slice.

    With litres = [1098, 1125, 1141, 1087, 1160, 1152, 1119], the Check calls them on the whole week (total 7882, best 1160), on &litres[..3] (3364 and 1141), on &litres[..2] (2223 and 1125), on &litres[4..] (3431 and 1160), on the one day &litres[3..4] (1087 and 1087), and on the empty &litres[0..0] (0 and 0). It also calls best(&[0, 0, 0]) and expects 0.

  3. Task 3

    report.rs: a line added to a borrowed report

    Write pub fn add_line(report: &mut String, farmer: &str, paise: u64) in report.rs. It borrows the report mutably and adds one line at its end: the farmer, a space, ₹, the rupees, a point, the paise as two digits, and a line break. It returns nothing: the caller keeps the report, now one line longer. Push onto the String it borrows: the Check looks at where the report's text lives afterwards.

    The Check starts with the report "Napad, morning\n" and calls add_line(&mut report, "F10650", 10956), expecting "Napad, morning\nF10650 ₹109.56\n"; then F10663 with 48697 and F10001 with 5, expecting the lines F10663 ₹486.97 and F10001 ₹0.05 after it. On an empty report, add_line(&mut report, "F14758", 38082) gives "F14758 ₹380.82\n".

  4. Task 4 · interview question

    Interview: society.rs, the slice and the push

    Lakhan wrote society.rs, a program of its own (cargo run --bin society): it takes the society's id from the start of the report as a slice, adds the evening line, and prints both. It does not compile. Fix it so that it prints exactly:

    Society: S001

    S001 morning: 211 cans

    S001 evening: 195 cans

    Keep first as the slice &report[0..4], with no copy of the text: no clone, to_string, to_owned or format! (the Check looks). Keep the line that makes report and the line that pushes the evening as they are: the Check also runs it with S014's shift in them, and then it must print Society: S014, S014 morning: 66 cans and S014 evening: 54 cans.

    Farhan will ask: why does the compiler refuse to push to report while first is still in use?

What you will learn

  • References: & lends a value to read, &mut lends it to change.
  • The borrowing rules: many readers, or one writer, never both; errors E0502 and E0499.
  • Slices: &s[0..4] is part of a text, &a[..3] part of an array.
  • &str and &[u32] parameters: one function for a String, a literal, or a part of either.
  • Text methods that borrow: trim, split, starts_with, contains, find.
  • No dangling references: E0106, and why Rust can promise it.

More in The language

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