#[derive(Debug,Default)]
struct C<T>(T, Option<Box<C<T>>>);
impl<T: Default> C<T> {
fn get(&mut self) -> Self {
let mut cur = self;
while let Some(x) = cur.1.as_mut() {
cur = x.as_mut();
}
// Ok
// while cur.1.is_some(){
// cur = cur.1.as_mut().unwrap().as_mut();
// }
std::mem::take(cur) // Error
}
}
why cur.1.as_mut borrow continues after while loop, so that `std::mem::take(cur)` line can not compile
1 Like
It's a limitation of the current borrow checker, unfortunately. The let Some(x) is not released with while, unlike if.
You can work around as you did, or with something like this (a bit ugly, but is optimized correctly by the compiler):
while true {
if cur.1.is_none() {
break;
}
let x = cur.1.as_mut().unwrap();
cur = x.as_mut();
}
Or you can use the polonius-the-crab crate for more complex situations.
4 Likes
system
Closed
3
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.