In the following code, it seems like the rust compiler has a problem with a borrow being dropped at the end of the code's execution. Even if I wrap the for loop in brackets so it has it's own scope it doesn't seem to recognize that the borrow comes to an end.
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);
}
Compile error:
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