获取 move closure 的引用报错,请指正问题所在
有下面的代码
1. fn boxed_closure(closures: &mut Vec<&dyn Fn()>) {
2. let v = "abc".to_string();
3. let v = 1;
4. closures.push(&||println!("first"));
5. closures.push(&|| println!("second"));
6. closures.push(&move || println!("v's value:{}",v));
7. }
8.
9. fn main() {
10. let mut closures:Vec<&dyn Fn()> = vec![];
11.
12. boxed_closure(&mut closures);
13. }
在函数 boxed_closure 中,第 4 行和第 5 行都没有报错,但是第6行报错:
1 | fn boxed_closure(closures: &mut Vec<&dyn Fn()>) {
| - let's call the lifetime of this reference `'1`
...
6 | closures.push(&move || println!("v's value:{}",v));
| ---------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-- temporary value is freed at the end of this statement
| | |
| | creates a temporary value which is freed while still in use
| argument requires that borrow lasts for `'1`
看了rust 的 temporary lifetime extentsion 的相关文档没有找到问题的原因,因为文档中就没有提到 move closure 相关的临时对象。
我猜测报错的原因是,move closure 虽然把 v 的所有权转移到 closure 中,但是rust仍然认为 closure 使用的是函数 boxed_closure 中局部变量 v 的 &v,所以导致编译失败。
请哪位大牛解答一下,谢谢!
推荐文章: