Rust · Chapter 15 of 26

Lifetimes

By the end of this chapter you can say why every reference has a lifetime, read the compiler's errors when one would dangle, write lifetime parameters on functions that return a reference, know when you can leave them out, keep references inside a struct, parse text without copying it, and say what 'static means. 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

The box is a small machine, and it parses all day: 211 analyser lines in S001's morning, a line every few seconds at the busiest counters. The Rust you know can parse a line by copying each field into a String with to_string(). That works, and costs one allocation for every field of every line: for the time, farmer and kind of S001's morning alone, 627 allocations and 4,021 bytes copied, measured below. The text is already in memory; the fields are just parts of it. Chapter 6 showed the cheap way, a &str slice that points into the text, and functions like trim that return one.

Try to go further with slices and the compiler starts asking questions. A function that takes two times and returns the later one does not build:

fn later(a: &str, b: &str) -> &str {
    if a > b { a } else { b }
}
error[E0106]: missing lifetime specifier
 --> e0106.rs:1:31
  |
1 | fn later(a: &str, b: &str) -> &str {
  |             ----     ----     ^ expected named lifetime parameter
  |
  = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `a` or `b`
help: consider introducing a named lifetime parameter
  |
1 | fn later<'a>(a: &'a str, b: &'a str) -> &'a str {
  |         ++++     ++          ++          ++

Chapter 6 promised that this error would get its own chapter. A struct that keeps slices of a line hits the same wall. To parse without copying, you need to tell the compiler how long each reference may live: its lifetime.

What you build: 4 tasks

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

  1. Task 1

    field.rs: one field of a line, borrowed

    Write pub fn field<'a>(line: &'a str, n: usize) -> Option<&'a str> in field.rs, with the lifetime written out (the starter leaves it out; the Check reads field.rs for a named lifetime). It returns field n of a comma-separated line, counting from 0, as a slice of the line itself, or None when the line has fewer fields. An empty line has one field, the empty one.

    With line = "06:02:07,F10122,cow,4.88,4.2,8.6", the Check expects field(line, 0) Some("06:02:07"), field(line, 1) Some("F10122"), field(line, 5) Some("8.6") and field(line, 6) None; field("07:55:03,F1013", 2) None; and field("", 0) Some(""). It also checks that every slice it gets back lies inside the line it gave.

  2. Task 2

    log_line.rs: a LogLine that borrows from the log

    LogLine<'a> in log_line.rs has six pub fields, all &'a str: time, farmer, kind, litres, fat and snf. Write pub fn parse_line<'a>(line: &'a str) -> Option<LogLine<'a>>, which returns Some when the line has exactly 6 comma-separated fields (taken as they are, even if empty) and None otherwise, and pub fn parse_log<'a>(log: &'a str) -> Vec<LogLine<'a>>, a LogLine for every line of the log with 6 fields, in order. Every field must be a slice of the text it was given: no String made, no text copied (the Check compares where each field lies in memory).

    The Check expects parse_line("06:02:07,F10122,cow,4.88,4.2,8.6") to be Some(LogLine { time: "06:02:07", farmer: "F10122", kind: "cow", litres: "4.88", fat: "4.2", snf: "8.6" }), None for "", "07:55:03,F1013" and "a,b,c,d,e,f,g", and Some with litres "" for "06:47:18,F10128,buffalo,,7.2,9.2". parse_log(doodh::analyser_log()) must give 209 LogLines, the first 06:01:32, F10077, 15.85 litres, the last F10091's; parse_log("") none.

  3. Task 3

    names.rs: a name from one of two borrowed places

    Write display_name(farmer: &Farmer, nickname: Option<&str>) -> &str in names.rs. It returns the nickname trimmed of spaces when it is Some and not blank, else farmer.name, always as a slice of one of the two, never a new String. The starter's signature gives farmer the lifetime 'a, the nickname another one, 'b, and the result 'a: it promises the result borrows only from farmer, so returning the nickname does not compile. Change the signature so the result may borrow from both (keep it pub, with its name and parameters).

    With f = doodh::farmer("F10001") (Pravinbhai Bhatt), the Check expects display_name(&f, Some(" Raju ")) to be "Raju" (a slice of the nickname it gave), display_name(&f, Some(" ")) and display_name(&f, None) "Pravinbhai Bhatt" (a slice of f.name). With F10013 (Kantaben Bharwad) it expects Some("Kanta") to give "Kanta" and Some("") "Kantaben Bharwad".

  4. Task 4 · interview question

    Interview: slip.rs, the slip line that will not build

    slip.rs is a program of its own (cargo run --bin slip, and the Check builds it alone). Lakhan's two functions each return a reference to a String made inside the function, so neither compiles (E0515). Fix them in two different ways: slip_line(farmer: &str, ml: u32) must return an owned String; slip_into(buf: &'a mut String, farmer: &str, ml: u32) must keep returning &'a str, by clearing buf, writing the line into it and returning a slice of buf.

    Keep main's lines let first = slip_line("F10150", 9160); and let second = slip_into(&mut buf, "F10018", 9110); exactly as they are. It must print exactly:

    F10150: 9160 ml

    F10018: 9110 ml

    The Check also changes those two lines to slip_line("F14800", 12345) and slip_into(&mut buf, "F10001", 2010), and then it must print F14800: 12345 ml and F10001: 2010 ml. It also calls slip_into a second time on the same buf with F10002 and 7 ml, which must print F10002: 7 ml alone (buf cleared first).

    Farhan will ask: why can a function never return a reference to its own local String, and of your two fixes, which is better for the box, and when is the other one worth it?

What you will learn

  • Lifetimes: how long a reference is valid, and the errors when it would outlive its value (E0597, E0515).
  • Lifetime parameters: fn later<'a>(a: &'a str, b: &'a str) -> &'a str, and what they promise.
  • The three elision rules: when you may leave lifetimes out.
  • Structs that hold references: struct Row<'a> { village: &'a str, .. }.
  • Parsing without copying: allocations counted, slices against Strings.
  • 'static: references valid for the whole program.

More in Traits and data

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