How can I reassign two variables when one has a reference to the other?

Here's a playground link: Rust Playground

struct A(i32);
struct B<'x>(&'x A);
impl Drop for B<'_> {
    fn drop(&mut self) { }

pub fn main() {
    let mut a = A(0);
    let mut b = B(&a);
    println!("{}", b.0.0);

    a = A(1);
    b = B(&a);
    println!("{}", b.0.0)

This program doesn't compile because a is borrowed by b and cannot be reassigned. The borrow will end when b is reassigned, but that's too late. What's a good way to change both a and b at the same time?

If you really must have these two mutable variables, then you need to manually drop b before re-assigning a.

1 Like

Thanks, that should do it. I didn't realise the inferred lifetime was excessive and I could just shorten it.

The lifetime wasn't excessive -- it had to be alive during the drop of the original b value when you assign a new value. It's a use of the lifetime, if you will. By changing the drop location, you change where the lifetime has to be alive.