How to visit the field of a mutable object after it's mutally borrowed

struct A {
    pub id: i32
}

struct RefBox<'a> {
    pub inner:Option<&'a mut A>

}

fn main() {
    let mut a = A {
        id: 100
    };

    let mut ref_box = RefBox {
        inner:None
    };

    let ref_box_ref = &mut ref_box;
    move_mut_ref(&mut a, ref_box_ref);

    if let Some(f) = ref_box_ref.inner.as_mut() {
        println!("value {}", f.id);
    }
}

fn move_mut_ref<'a>(a: &'a mut A, ref_box: &'a mut RefBox<'a>) {
    ref_box.inner = Some(a);
}

the code won't compile, compilation error is

my question is how to visit a.id through ref_box_ref after the function move_mut_ref is invoked?

Change your function parameter to a shorter (implicit) lifetime, ref_box: &mut RefBox<'a>, so you're not borrowing it for its entire life.

1 Like

Thanks a lot, your suggestion solve my problem. i think i need to read the documentation about lifetime again.

I guess we could benefit from some help messages pointing out instances of &'a mut Foo<'a> types (mutable reference to type containing another instance of the same lifetime argument as the reference) as “problematic” or even “probably wrong” when they are causing problems at the call-site? IDK, the “when they are causing problems” might be tricky though… I have never looked into borrow checking implementation yet.

1 Like

Maybe that could be a clippy lint, at least? I think that would get in before borrowck errors out.

1 Like

Does clippy get to run when borrowck failed? My recollection was that it didn't if typeck failed, for example...

I don't know, but my thought of running before borrowck is that it could flag &'a mut Foo<'a> as a code smell -- not sure if that will be noisy for legitimate uses though.

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.