Is there a better way to fix this
Yes, but not in stable Rust. You need non-lexical lifetimes:
#![feature(nll)]
#[derive(Debug)]
struct Foo(u32);
fn get_foo(bar: &mut Foo) -> Option<&mut u32> {
Some(&mut bar.0)
}
pub fn test() {
let x = 5;
let y = 6;
let mut a = Foo(x);
let b = get_foo(&mut a);
if let Some(value) = b {
*value = y;
}
println!("{:?}", a);
}
fn main() {}
Until then, just use the extra block.
Dropping the value of b doesn’t work either
drop
has nothing to do with borrows.
See also:
- Moved variable still borrowing after calling `drop`?
- What are the options to end a mutable borrow in Rust?
- Why is a borrow still held in the else block of an if let?
- Rust borrow of a HashMap lasts beyond the scope it’s in?
- How to end a borrow in a match or if let expression?
- Borrow checker and function arguments in Rust, correct or over zealous?
2
solved Dropping partially moved values after the moved values are dropped