Rust Lifetimes Function Parameters (Input Lifetimes)


Example

fn foo<'a>(x: &'a u32) {
    // ...
}

This specifies that foo has lifetime 'a, and the parameter x must have a lifetime of at least 'a. Function lifetimes are usually omitted through lifetime elision:

fn foo(x: &u32) {
    // ...
}

In the case that a function takes multiple references as parameters and returns a reference, the compiler cannot infer the lifetime of result through lifetime elision.

error[E0106]: missing lifetime specifier
1 | fn foo(bar: &str, baz: &str) -> &i32 {
  |                                 ^ expected lifetime parameter

Instead, the lifetime parameters should be explicitly specified.

// Return value of `foo` is valid as long as `bar` and `baz` are alive.
fn foo<'a>(bar: &'a str, baz: &'a str) -> &'a i32 {

Functions can take multiple lifetime parameters too.

// Return value is valid for the scope of `bar`
fn foo<'a, 'b>(bar: &'a str, baz: &'b str) -> &'a i32 {