Duration of a mutable borrow/reference in a struct

A simplified version of what I'd like to achieve:

I previously used Rc<RefCell<A>> but I was wondering if I could avoid that altogether and work with references instead. The child struct should be able to mutate the parent struct, but the two will never attempt to mutate within the same scope.

struct A<'parent> {
    parent_a: Option<&'parent mut A<'parent>>,
    field: i32,

impl<'parent> A<'parent> {
    pub fn new() -> Self {
        A{parent_a: None, field: 0}
    pub fn new_from_parent(parent_a: &'parent mut A<'parent>) -> Self {
        A{parent_a: Some(&mut *parent_a), field: 0}

fn main() {
    let mut outer = A::new();
    { // Enter some sort of scope, like function where outer is a param
        let mut inner = A::new_from_parent(&mut outer);
        inner.field = 1;
    } // I want the borrow to end here but the lifetime of the borrow is as long as the original
    println!("{}", outer.field);  // Does not compile since mutable borrow above, immutable borrow here

How can I indicate the duration of the borrow? I'm OK with the child struct living as long as the parent struct if it needs to, but I'd also like the mutable borrow to be dropped when the child struct has gone out of scope.

&'lt mut Type<'lt> is a well-recognizable anitpattern. It is almost never what you want, since it forces the mutable borrow to last for the entire lifetime of the object, effectively making it unusable after it's borrowed. My previous answer to an identical question explains this in more detail. TL;DR: you should probably stick with RefCell in this specific case.

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.