当我尝试编译这段代码(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
我明白错误提示有助于我在上一行声明闭包,如下所示:
let f = &|c: &char| c.is_digit(10);
(有效代码),但为什么这是必要的呢?我也不确定为什么闭包需要包含两个引用-
&|c: &char|
。难道"abc123".chars()
不只是创建了一个字符的迭代器吗?