在以下代码中,似乎rust编译器存在问题,即在代码执行结束时删除了借项。即使我将for循环放在方括号中,使其具有自己的作用域,也似乎无法识别借用即将结束。
use std::ops::RangeBounds;
use std::any::Any;
pub trait UpdateTables<T> {
fn apply_first<'a>(&mut self, table: &'a mut T) -> Box<dyn Any + 'a>;
}
struct Drain<R>
where
R: 'static + Clone + RangeBounds<usize>,
{
pub r: R,
}
impl<T, R> UpdateTables<Vec<T>> for Drain<R>
where
R: 'static + Clone + RangeBounds<usize>,
{
fn apply_first<'a>(&mut self, table: &'a mut Vec<T>) -> Box<dyn Any + 'a> {
Box::new(table.drain(self.r.clone()))
}
}
fn main() {
let mut v = vec![1, 2, 4, 5, 7, 8];
let mut d = Drain {
r: (1..),
};
println!("{:?}", &v);
for i in d.apply_first(&mut v).downcast::<std::vec::Drain<'_, i32>>().unwrap() {
println!("{:?}", i);
}
println!("{:?}", &v);
}
编译错误:
error[E0597]: `v` does not live long enough
--> src/main.rs:32:28
|
32 | for i in d.apply_first(&mut v).downcast::<std::vec::Drain<'_, i32>>().unwrap() {
| --------------^^^^^^-
| | |
| | borrowed value does not live long enough
| argument requires that `v` is borrowed for `'static`
...
37 | }
| - `v` dropped here while still borrowed
error[E0502]: cannot borrow `v` as immutable because it is also borrowed as mutable
--> src/main.rs:36:22
|
32 | for i in d.apply_first(&mut v).downcast::<std::vec::Drain<'_, i32>>().unwrap() {
| ---------------------
| | |
| | mutable borrow occurs here
| argument requires that `v` is borrowed for `'static`
...
36 | println!("{:?}", &v);
| ^^ immutable borrow occurs here
循环不是问题。在此简化示例中,错误相同:
use std::any::Any;
fn apply_first<'a, T>(table: &'a mut Vec<T>) -> Box<dyn Any + 'a> {
Box::new(table.drain(1..))
}
fn main() {
let mut v = vec![1, 2, 4, 5, 7, 8];
let _ = apply_first(&mut v);
println!("{:?}", &v);
}
error[E0597]: `v` does not live long enough
--> src/main.rs:9:25
|
9 | let _ = apply_first(&mut v);
| ------------^^^^^^-
| | |
| | borrowed value does not live long enough
| argument requires that `v` is borrowed for `'static`
10 | println!("{:?}", &v);
11 | }
| - `v` dropped here while still borrowed
error[E0502]: cannot borrow `v` as immutable because it is also borrowed as mutable
--> src/main.rs:10:22
|
9 | let _ = apply_first(&mut v);
| -------------------
| | |
| | mutable borrow occurs here
| argument requires that `v` is borrowed for `'static`
10 | println!("{:?}", &v);
| ^^ immutable borrow occurs here
核心问题是Any
仅适用于'static
类型,因此dyn Any + 'a
毫无意义,并暗示'a: 'static
。我希望编译器是一个小更多的信息有关,其中的'static
约束来自何处,但我离题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句