When I try to compile this code (playground):
fn main() {
let iter = "abc123".chars().filter(&|&c: &char| c.is_digit(10));
match iter.clone().take(3).count() {
3 => println!("{}", iter.collect::<String>()),
_ => {}
}
}
I get the following error:
error: borrowed value does not live long enough
--> test.rs:2:41
|
2 | let iter = "abc123".chars().filter(&|c: &char| c.is_digit(10));
| ^^^^^^^^^^^^^^^^^^^^^^^^^ - temporary value only lives until here
| |
| temporary value created here
...
7 | }
| - temporary value needs to live until here
|
= note: consider using a `let` binding to increase its lifetime
I understand that the error is helpfully telling me to declare the closure in the line above with let f = &|c: &char| c.is_digit(10);
(working code), but why exactly is this necessary?
I'm also not sure why the closure has to contain two references - &|c: &char|
. Doesn't "abc123".chars()
simply create an iterator of chars?