Can a standalone closure take `&str` and return `&str` with the same lifetime?

Viewed 112

Code:

fn main() {
    let f = |str: &str| str.trim();
    println!("{}", f("  foo bar  "));
}

Error:

error: lifetime may not live long enough
 --> src/main.rs:2:25
  |
2 |     let f = |str: &str| str.trim();
  |                   -   - ^^^^^^^^^^ returning this value requires that `'1` must outlive `'2`
  |                   |   |
  |                   |   return type of closure is &'2 str
  |                   let's call the lifetime of this reference `'1`

Playground

The same closure works if used as an argument to a function, e.g. vec.iter().map(|str| str.trim()).

Is it possible for a standalone closure, like in my code, to take &str and return &str with the same lifetime?

1 Answers
Related