Rust Playbook

Course › Week 2 · Errors, collections, traits › Day 5 · lesson 12 of 42 · 15 min reading + 60–90 min practice

Lifetimes and tests

Read lifetime annotations, and test your code with #[test] and cargo test.

lifetimes'a#[test]assert_eq!cargo test

On this page
  1. 1. Which input does the result borrow from?
  2. 2. Reading 'a
  3. 3. What the promise protects
  4. 4. Why you almost never write them
  5. 5. Tests live next to the code
  6. 6. What a failing test looks like
  7. 7. Testing errors
  8. 8. Running some of them
  9. Coming from PHP
  10. Practice
  11. Remember

Two unrelated topics, kept short. Lifetimes: just enough to read 'a in a signature and fix the one error that asks for it. This course never needs more. Tests: Rust has a test runner built in, and from today every tool you write has tests.

1. Which input does the result borrow from?

A function that returns a reference must make clear what it borrows from, so the compiler can check the result is not used after that thing is gone. With one reference parameter, the answer is obvious. With two, the compiler cannot guess:

src/main.rsdoes not compile
fn longer(a: &str, b: &str) -> &str {
    if a.len() >= b.len() { a } else { b }
}

fn main() {
    println!("{}", longer("Payment failed", "Deadlock"));
}
cargo build
error[E0106]: missing lifetime specifier
 --> src/main.rs:1:32
  |
1 | fn longer(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 longer<'a>(a: &'a str, b: &'a str) -> &'a str {
  |          ++++     ++          ++          ++

For more information about this error, try `rustc --explain E0106`.
error: could not compile `hello` (bin "hello") due to 1 previous error

2. Reading 'a

A lifetime is a name for “how long a reference is valid”, written with an apostrophe: 'a. The compiler’s suggestion reads: “there is some span 'a; both inputs live at least that long, and the result is valid for that span too”. In other words, the result may borrow from either input, so it lives no longer than the shorter of them.

src/main.rs
fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a.len() >= b.len() { a } else { b }
}

fn main() {
    println!("{}", longer("Payment failed", "Deadlock"));
}
$ cargo run
Payment failed

A lifetime annotation changes nothing at runtime. It is a promise in the signature that the compiler checks at every call.

3. What the promise protects

Here the result might point into b, and b is freed at the end of the inner block, before the result is printed:

src/main.rsdoes not compile
fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a.len() >= b.len() { a } else { b }
}

fn main() {
    let a = String::from("Deadlock");
    let result;
    {
        let b = String::from("Payment failed");
        result = longer(&a, &b);
    }
    println!("{result}");
}
cargo build
error[E0597]: `b` does not live long enough
  --> src/main.rs:10:29
   |
 9 |         let b = String::from("Payment failed");
   |             - binding `b` declared here
10 |         result = longer(&a, &b);
   |                             ^^ borrowed value does not live long enough
11 |     }
   |     - `b` dropped here while still borrowed
12 |     println!("{result}");
   |                ------ borrow later used here

For more information about this error, try `rustc --explain E0597`.
error: could not compile `hello` (bin "hello") due to 1 previous error

This is the dangling reference of Day 4, caught across a function call. Without the annotation, the compiler could not know that result depends on b.

4. Why you almost never write them

Every function on this site so far that returned a &str had one reference parameter, like Day 4’s level_of(line: &str) -> &str. For that case, and for methods taking &self, the compiler fills the lifetime in itself (“lifetime elision”). You write them only when it asks, and it always asks with this same E0106 error and the fix in its help:.

SignatureNeeds 'a?Why
fn level_of(line: &str) -> &strNoOne input reference: the result borrows from it
fn summary(&self) -> &strNoA method: the result borrows from self
fn longer(a: &str, b: &str) -> &strYesTwo inputs: which one?
fn default_note() -> &strReturn a StringNo input to borrow from (Day 4)

'static

'static is the one lifetime with a name of its own: it lasts for the whole program. String literals are &'static str, because they are built into the executable. You saw it in fn label(level: &Level) -> &'static str on Day 1 of this week: each label is a literal, so it lives forever.

5. Tests live next to the code

A test is a function marked #[test]. By convention, a file’s tests go in a module called tests at the bottom, marked #[cfg(test)] so it is only compiled when testing. use super::*; brings in everything from the file above it.

assert_eq!(actual, expected) fails the test if the two differ. It needs PartialEq and Debug on what it compares, which Option, tuples and &str all have.

src/lib.rs
/// The level and message of an entry's first line, borrowed from the line itself.
pub fn split_entry(line: &str) -> Option<(&str, &str)> {
    if !line.starts_with('[') {
        return None;
    }
    let (head, message) = line.split_once(": ")?;
    let (_, level) = head.rsplit_once('.')?;
    Some((level, message))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn splits_an_entry() {
        let line = "[2026-11-30 09:41:03] production.ERROR: Deadlock found";
        assert_eq!(split_entry(line), Some(("ERROR", "Deadlock found")));
    }

    #[test]
    fn keeps_colons_inside_the_message() {
        let line = "[2026-11-30 09:41:03] production.ERROR: SQLSTATE[40001]: Serialization failure";
        assert_eq!(
            split_entry(line),
            Some(("ERROR", "SQLSTATE[40001]: Serialization failure"))
        );
    }

    #[test]
    fn ignores_stack_trace_lines() {
        assert_eq!(
            split_entry("#0 /var/www/app/Actions/ConfirmBooking.php(41)"),
            None
        );
        assert_eq!(split_entry("[stacktrace]"), None);
    }
}
$ cargo test
running 3 tests
test tests::ignores_stack_trace_lines ... ok
test tests::keeps_colons_inside_the_message ... ok
test tests::splits_an_entry ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

cargo test compiles a test build and runs every #[test] function, in parallel. The second test is the kind that pays off: a message that itself contains ": ", which a careless parser would cut in the wrong place.

split_entry returns two slices of line with no annotation: one input reference, so elision applies, as in section 4.

6. What a failing test looks like

A bug in the parser: it uses split_once for the level too, so it cuts at the first dot instead of the last. The test that catches it:

src/lib.rs
pub fn split_entry(line: &str) -> Option<(&str, &str)> {
    if !line.starts_with('[') {
        return None;
    }
    let (head, message) = line.split_once(": ")?;
    let (_, level) = head.split_once('.')?;
    Some((level, message))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn handles_a_dotted_environment_name() {
        let line = "[2026-11-30 09:41:03] staging.eu.ERROR: Deadlock found";
        assert_eq!(split_entry(line), Some(("ERROR", "Deadlock found")));
    }
}
$ cargo test
running 1 test
test tests::handles_a_dotted_environment_name ... FAILED

failures:

---- tests::handles_a_dotted_environment_name stdout ----

thread 'tests::handles_a_dotted_environment_name' (5453) panicked at src/lib.rs:17:9:
assertion `left == right` failed
  left: Some(("eu.ERROR", "Deadlock found"))
 right: Some(("ERROR", "Deadlock found"))
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace


failures:
    tests::handles_a_dotted_environment_name

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

left is what the code returned, right what the test expected. Environment names with a dot are rare, which is exactly why a test should say how they are handled before production finds out.

7. Testing errors

For a function that returns a Result, test both sides. assert!(condition) fails when the condition is false; is_err() and is_ok() say which variant you got.

src/lib.rs
pub fn parse_nights(input: &str) -> Result<u32, String> {
    let nights: u32 = input
        .trim()
        .parse()
        .map_err(|_| format!("'{input}' is not a number of nights"))?;
    if nights == 0 || nights > 365 {
        return Err(format!("{nights} nights is outside 1 to 365"));
    }
    Ok(nights)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn accepts_a_valid_number() {
        assert_eq!(parse_nights(" 14 "), Ok(14));
    }

    #[test]
    fn rejects_zero_and_too_many() {
        assert!(parse_nights("0").is_err());
        assert!(parse_nights("366").is_err());
    }

    #[test]
    fn explains_what_was_wrong() {
        assert_eq!(
            parse_nights("a week"),
            Err(String::from("'a week' is not a number of nights"))
        );
    }
}
$ cargo test
running 3 tests
test tests::accepts_a_valid_number ... ok
test tests::explains_what_was_wrong ... ok
test tests::rejects_zero_and_too_many ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

Comparing the whole Err checks the message too. With your own error enum, add #[derive(Debug, PartialEq)] to it and compare variants the same way.

unwrap() is fine inside tests: if it panics, the test fails with a clear message, which is what you want there.

8. Running some of them

CommandRuns
cargo testEvery test in the package
cargo test dottedTests whose name contains dotted
cargo test -- --nocaptureEverything, showing what tests print (hidden by default)

Tests in a tests/ folder next to src/ are integration tests: they use your library from outside, like another crate would. Week 5 uses them for the axum service.

Coming from PHP

The first test in Pest, for comparison:

tests/Unit/SplitEntryTest.php
<?php

it('splits an entry', function () {
    $line = '[2026-11-30 09:41:03] production.ERROR: Deadlock found';

    expect(splitEntry($line))->toBe(['ERROR', 'Deadlock found']);
});

PHP needs a framework installed (Pest or PHPUnit) and tests in a separate folder. Rust’s test runner is part of cargo, and unit tests sit in the same file as the code, where they can also test private functions. Lifetimes have no PHP equivalent at all: PHP never has a reference to freed memory, because its garbage collector keeps everything alive as long as something points at it.

PracticeThe Book ch. 10.3 and 11, Rustlings lifetimes and tests

Read chapter 10.3 once for the idea (do not try to master it) and chapter 11 properly.

In Rustlings: 16_lifetimes, 17_tests.

Exercise: tests for your split logstat

In the split logstat from Day 1 of this week, add a tests module to the file with entry_level. Cover: a normal entry for two different levels, an unknown level, a stack-trace line, [stacktrace], an empty line, and a message containing ": ". Then break entry_level on purpose and watch the right test fail.

Remember

  • Write a lifetime only when the compiler asks, and then it is the 'a in its help: line.
  • Tests live in a #[cfg(test)] mod tests at the bottom of the file they test; test the edges, not only the happy path.

Tomorrow is a build day: logstat v2, with real command-line flags, a proper error type and tests.