Skip to content

Store a Borrowed View in a Struct

The Course
•
28 min study

A row such as 7,Rust Patterns has two fields. A parser can return them as a pair of slices, (&str, &str), but a pair has no names, and it is easy to swap .0 and .1 by mistake. A struct gives the slices names. Because the fields are borrowed, the struct needs a lifetime parameter: struct Row<'a> with fields of type &'a str says that a Row points into some text and cannot be used after that text is gone. Moving or returning a Row moves only the two references; the original String still owns the bytes.

In a signature, Row<'_> means "a Row borrowing from the input, with the lifetime filled in by elision". With one borrowed input, that is the same as writing fn fields<'a>(line: &'a str) -> Option<Row<'a>>. The body uses map on an Option: it runs the closure for Some and passes None through unchanged. The closure |(id, title)| Row { id, title } is a small unnamed function written in place: the part between the bars is its parameter, here a pattern that unpacks the pair, and the rest is its body, which builds a Row. Day 4 opens its iterator lesson with a full section on closures: how they differ from fn, and how they borrow the variables they use.

Predict and run

Which value owns the words? What do the Row fields display?

Predict, then run Rust
struct Row<'a> {
    id: &'a str,
    title: &'a str,
}

fn fields(line: &str) -> Option<Row<'_>> {
    line.split_once(',').map(|(id, title)| Row { id, title })
}

fn main() {
    let line = String::from("7,Rust Patterns");
    if let Some(row) = fields(&line) {
        println!("#{} {}", row.id, row.title);
    }
}
Check your prediction
Text
#7 Rust Patterns

line owns the text. split_once(',') finds the first comma and returns the parts before and after it, both slices of line, and the Row just labels them. Remove the comma from the input and predict the output: split_once returns None, map passes it through, and the if let block is skipped, so nothing prints.

A Row cannot outlive its line

Leaving out the lifetime is not an option. struct Row { id: &str, title: &str } fails with error[E0106]: missing lifetime specifier, once for each field, because a struct must say where its references come from. The lifetime then lets the compiler stop misuse at the call site:

Rust
let row;
{
    let line = String::from("7,Rust Patterns");
    row = fields(&line);
}
if let Some(row) = row {
    println!("{}", row.title);
}

This reports error[E0597]: line does not live long enough. The String is dropped at the end of the block, so any Row pointing into it would point at freed memory. In languages without this check, that bug compiles and fails later, or prints garbage.

Many rows from one input

Borrowed rows are most useful when one input holds many records. Below, every Row in the vector points into the same text, and no title is copied. The method returns &'a str, the lifetime of the input text, rather than a borrow of the Row itself.

Borrow every row from one text Rust
struct Row<'a> {
    id: &'a str,
    title: &'a str,
}

impl<'a> Row<'a> {
    fn title(&self) -> &'a str {
        self.title.trim()
    }
}

fn fields(line: &str) -> Option<Row<'_>> {
    line.split_once(',').map(|(id, title)| Row { id, title })
}

fn main() {
    let text = String::from("7, Rust Patterns\nbroken line\n9, Iterator Notes");
    let mut rows = Vec::new();
    for line in text.lines() {
        match fields(line) {
            Some(row) => rows.push(row),
            None => println!("Skipped: {line}"),
        }
    }
    let first_title = rows[0].title();
    for row in &rows {
        println!("#{} {}", row.id, row.title());
    }
    drop(rows);
    println!("First title still readable: {first_title}");
}
Text
Skipped: broken line
#7 Rust Patterns
#9 Iterator Notes
First title still readable: Rust Patterns

impl<'a> Row<'a> declares the lifetime for the impl block, just as impl<T> declares a type. text.lines() yields slices of text, so each row borrows from text, not from the temporary line. Because title returns &'a str, first_title borrows from text too, and stays valid after the vector of rows is dropped. Had the method returned a plain &str, elision would have tied it to &self, and the drop(rows) line would be rejected with error[E0505]: cannot move out of rows because it is borrowed.

Borrow while parsing, own when keeping

Borrowed structs are ideal for short-lived work such as parsing and reporting. When a value must outlive its input, for example a title stored in the queue after the line is gone, convert it with String::from while the input is still alive.

Practice

Exercise

Your turn

Parse "7, Rust Patterns " with fields, print Read #7, and keep the trimmed title as an owned String. The input String must be created and dropped inside an inner block, and main prints Saved: Rust Patterns after that block.

Your working space Rust
struct Row<'a> {
    id: &'a str,
    title: &'a str,
}

fn fields(line: &str) -> Option<Row<'_>> {
    line.split_once(',').map(|(id, title)| Row { id, title })
}

fn main() {
    let line = String::from("7, Rust Patterns ");
    // Convert the borrowed title before line goes out of scope.
    if let Some(row) = fields(&line) {
        println!("#{} {}", row.id, row.title.trim());
    }
}
Hint 1: the idea

Do the ownership conversion while the input is still alive. A block in Rust is an expression, so it can produce the owned value as its result.

Hint 2: a first step

Write let saved = { ... };, move line into that block, and end the block with String::from(row.title.trim()) without a semicolon.

Worked solution
Run the solution Rust
struct Row<'a> {
    id: &'a str,
    title: &'a str,
}

fn fields(line: &str) -> Option<Row<'_>> {
    line.split_once(',').map(|(id, title)| Row { id, title })
}

fn main() {
    let saved = {
        let line = String::from("7, Rust Patterns ");
        let Some(row) = fields(&line) else {
            panic!("expected two fields");
        };
        println!("Read #{}", row.id);
        String::from(row.title.trim())
    };
    println!("Saved: {saved}");
}
Text
Read #7
Saved: Rust Patterns

The new String owns its own copy of the bytes, so both the borrowed row and the input line can disappear at the end of the block. trim removes the space after the comma and the trailing space before the copy is made. Returning row.title itself from the block would fail with E0597, which is the error from earlier in this lesson. The checkpoint asks you to write such a parser yourself.

Was this article helpful?

Your response is saved on this device.