【发布时间】:2019-11-05 13:28:51
【问题描述】:
我想编写一个闭包,它接受一个对象并从中返回一个迭代器。这个想法是将闭包存储在一个结构中并根据需要应用:
fn main() {
let iter_wrap = |x: &String| Box::new(x.chars());
let test = String::from("test");
for x in iter_wrap(&test) {
println!("{}", x);
}
}
这会导致错误:
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
--> src/main.rs:2:45
|
2 | let iter_wrap = |x: &String| Box::new(x.chars());
| ^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the body at 2:21...
--> src/main.rs:2:21
|
2 | let iter_wrap = |x: &String| Box::new(x.chars());
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: ...so that reference does not outlive borrowed content
--> src/main.rs:2:43
|
2 | let iter_wrap = |x: &String| Box::new(x.chars());
| ^
note: but, the lifetime must be valid for the call at 5:14...
--> src/main.rs:5:14
|
5 | for x in iter_wrap(&test) {
| ^^^^^^^^^^^^^^^^
note: ...so that argument is valid for the call
--> src/main.rs:5:14
|
5 | for x in iter_wrap(&test) {
| ^^^^^^^^^^^^^^^^
我尝试将String改成Vec并去掉拳击,但结果是一样的。
如何编译?
【问题讨论】:
标签: rust iterator closures lifetime