Guide

Elision and 'static

Most functions that use references have no lifetime annotations at all. That is because Rust fills them in for you in common cases. This is called lifetime elision.

One reference in, one reference out

fn head(s: &str) -> &str {    &s[..2]}

There is only one reference input, so the output must borrow from it. Rust reads this as fn head<'a>(s: &'a str) -> &'a str. The link is still there: the result can't outlive s. With two reference inputs and no self, Rust can't guess, and you get E0106.

Methods and &self

In a method, a returned reference gets the lifetime of &self, even when there are other reference inputs.

impl User {    fn name(&self) -> &str {        &self.name    }}

The result borrows from the User, so the User must stay alive while you use it.

'static

'static means "valid for the whole program". String literals are &'static str, because the text is stored in the program itself.

fn greeting() -> &'static str {    "hello"}

Do not add 'static just to silence an error. It only works when the data really lives for the whole program.

Structs holding references

A struct that holds a reference needs a lifetime parameter.

struct Excerpt<'a> {    part: &'a str,}

This says an Excerpt can't outlive the text that part points to. Leaving out <'a> is error E0106. To add methods, write impl<'a> Excerpt<'a>, just like impl<T> for generics. Writing only impl Excerpt is error E0726.

Remember

  • One reference input: the output borrows from it.
  • Methods: the output borrows from self.
  • String literals are &'static str.
  • A struct with a reference field needs <'a>.