【发布时间】:2017-03-26 20:57:51
【问题描述】:
当我尝试编译这段代码时(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>()),
_ => {}
}
}
我收到以下错误:
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); (working code) 声明闭包,但为什么这是必要的呢?
我也不确定为什么闭包必须包含两个引用 - &|c: &char|。 "abc123".chars() 不是简单地创建一个字符的迭代器吗?
【问题讨论】:
-
相关:stackoverflow.com/q/31374051/155423;附近重复:stackoverflow.com/q/28776630/155423、stackoverflow.com/q/23969191/155423、working code; TL;DR:你可能想使用
by_ref。 -
@Shepmaster 我想我想问的是如何克隆一个迭代器(在我被错误消息弄糊涂之前)。那么,例如this,我该怎么做(我知道这不是最好的方法)。