How to deal with lifetime in closure?
⚓ Rust 📅 2025-12-26 👤 surdeus 👁️ 6I have following code:
impl StringExt for String {
fn replacement(&self) -> Self {
let replaced = NEWLINE_RE.replace_all(self, "\n");
let replaced = QUOTES_RE.replace_all(&replaced, "");
let replaced = LINKS_RE.replace_all(&replaced, |caps: &Captures| {
let caps_str: Vec<_> = caps
.iter()
.flat_map(|c| c.map(|c| c.as_str()))
.collect();
caps_str.last().unwrap()
//format!("{}", caps_str.last().unwrap())
});
replaced.into()
}
}
When I try to compile I'm getting following error about lifetimes:
error: lifetime may not live long enough
--> src/main.rs:72:13
|
67 | let replaced = LINKS_RE.replace_all(&replaced, |caps: &Captures| {
| ---- - return type of closure is &'2 &str
| |
| has type `®ex::Captures<'1>`
...
72 | caps_str.last().unwrap()
| ^^^^^^^^^^^^^^^^^^^^^^^^ returning this value requires that `'1` must outlive `'2`
error[E0515]: cannot return value referencing local variable `caps_str`
--> src/main.rs:72:13
|
72 | caps_str.last().unwrap()
| --------^^^^^^^^^^^^^^^^
| |
| returns a value referencing data owned by the current function
| `caps_str` is borrowed here
I can easily workaround it by using format, but of course I would like to know how to this proper. Using caps_str.last().cloned().unwrap() does not work either ![]()
Thanks!
3 posts - 3 participants
🏷️ Rust_feed