Skip to content

Tie a Returned Borrow to Its Input

The Course
•
28 min study

The queue reads commands such as add Rust. A helper that strips the word add and returns the rest can hand back a &str slice of the input instead of allocating a new String. That saves a copy, but it raises a question the compiler must answer at every call: how long may the caller keep the returned slice? It is only valid while the text it points into still exists.

When a function borrows exactly one input and returns a borrow, Rust assumes the result comes from that input. This rule is called lifetime elision, and it is why most functions need no lifetime syntax. With two borrowed inputs, there is no safe guess, so you say which one supplies the result. fn topic<'a>(line: &'a str, prefix: &str) -> Option<&'a str> declares a lifetime parameter 'a, attaches it to line and to the result, and leaves prefix out. Read it as: the result borrows from line, so it stays usable while line lives, whatever happens to prefix.

Predict and run

Can the returned slice still be printed after prefix leaves scope?

Predict, then run Rust
fn topic<'a>(line: &'a str, prefix: &str) -> Option<&'a str> {
    line.strip_prefix(prefix)
}

fn main() {
    let line = String::from("add Rust");
    let result;
    {
        let prefix = String::from("add ");
        result = topic(&line, &prefix);
    }
    println!("{result:?}");
}
Check your prediction
Text
Some("Rust")

prefix is dropped at the end of the inner block, but the signature says the result does not borrow from it. strip_prefix only uses the prefix to decide where to cut, and returns a slice of line. Because line is still alive at the println!, the program compiles. Now remove <'a> and both 'a annotations, run, and read the diagnostic before restoring them.

What the compiler cannot guess

Without the annotations, the signature becomes:

Rust
fn topic(line: &str, prefix: &str) -> Option<&str> {
    line.strip_prefix(prefix)
}

The compiler stops with error[E0106]: missing lifetime specifier, and its help line says the return type "contains a borrowed value, but the signature does not say whether it is borrowed from line or prefix". Notice that it checks the signature, not the body. Callers rely only on the signature, so it must carry the promise on its own.

The compiler also suggests a fix: put 'a on all three references. That compiles, but it promises more than needed. It would tie the result to prefix too, and the call in main would then fail, because prefix dies before the result is printed. The precise signature names only the input the result really comes from.

When either input may be returned

Sometimes the result really can come from either input. A function that returns the longer of two titles cannot know which one until it runs, so both inputs share 'a:

Return one of two borrowed titles Rust
fn longer<'a>(first: &'a str, second: &'a str) -> &'a str {
    if second.len() > first.len() { second } else { first }
}

fn main() {
    let queued = String::from("Rust Patterns");
    let typed = String::from("Rust");
    let result = longer(&queued, &typed);
    println!("Longer: {result}");
    println!("Tie keeps the first: {}", longer("Go", "JS"));
}
Text
Longer: Rust Patterns
Tie keeps the first: Go

Here the result is valid only while both strings live, because it could point into either. If typed is created in an inner block and dropped before result is printed, the program fails to compile with error[E0597]: typed does not live long enough, even though this particular call returned queued. The compiler reasons from the signature, which allows either answer. String literals such as "Go" live for the whole program, so they satisfy any lifetime.

A lifetime describes, it does not extend

Writing 'a never makes data live longer. It only tells the compiler how a returned reference relates to the inputs, so it can reject a caller that would use the reference after its data is gone.

Practice

Exercise

Your turn

Write without_suffix(title, suffix) that returns the title without the suffix, or None if the title does not end with it. The result borrows from the title only. In main, the suffix lives only inside an inner block; print the result after that block. Then call it again with the suffix " (final)". Expected output: Some("Rust"), then None.

Your working space Rust
fn main() {
    let title = String::from("Rust (draft)");
    {
        let suffix = String::from(" (draft)");
        println!("Suffix: {suffix}");
    }
    // Print the returned slice outside the block.
}
Hint 1: the idea

The returned text is a view of title. The suffix only tells the function how many bytes to remove, so it should not share the result's lifetime.

Hint 2: a first step

Copy the shape of topic: put 'a on title and inside the Option of the return type, and use strip_suffix. Declare let result; before the inner block and assign it inside.

Worked solution
Run the solution Rust
fn without_suffix<'a>(title: &'a str, suffix: &str) -> Option<&'a str> {
    title.strip_suffix(suffix)
}

fn main() {
    let title = String::from("Rust (draft)");
    let result;
    {
        let suffix = String::from(" (draft)");
        result = without_suffix(&title, &suffix);
    }
    println!("{result:?}");
    println!("{:?}", without_suffix(&title, " (final)"));
}
Text
Some("Rust")
None

The first result outlives suffix because its bytes belong to title. If you had written suffix: &'a str, the same main would be rejected with E0597. The None case shows the Option doing its job for a title without that ending. Next you store borrowed slices like these inside a struct.

Was this article helpful?

Your response is saved on this device.