Skip to content

Mutual referencing and self-referencing structures not possible with Vec, FnvIndexMap, SortedLinkedList but with std variants #296

Open
@systec-ms

Description

@systec-ms

Good day, sorry I don't really know how to name the problem, so here is a "minimal" example.

The following code will lead me into this error:

error[E0597]: `holder.b` does not live long enough
  --> src/main.rs:39:39
   |
39 |     holder.c.lookup.borrow_mut().push(&holder.b);
   |                                       ^^^^^^^^^ borrowed value does not live long enough
40 | }
   | -
   | |
   | `holder.b` dropped here while still borrowed
   | borrow might be used here, when `holder` is dropped and runs the destructor for type `Holder<'_>`
use core::cell::RefCell;

use heapless::{FnvIndexMap, Vec};

struct A {}

struct B<'a> {
    ref_a: RefCell<Option<&'a A>>,
}

struct C<'a> {
    lookup: RefCell<Vec<&'a B<'a>, 4>>,
}

struct Holder<'a> {
    c: C<'a>,
    b: B<'a>,
}

fn main() {
    let c = C {
        lookup: RefCell::new(Vec::new()),
    };

    let b = B {
        ref_a: RefCell::new(None),
    };

    let holder = Holder { c, b };

    holder.c.lookup.borrow_mut().push(&holder.b);
}

But with std::vec::Vec it is fine: lookup: RefCell<Vec<&'a B<'a>>>,
And also with a simple array.

use core::cell::RefCell;

use heapless::{FnvIndexMap, Vec};

struct A {}

struct B<'a> {
    ref_a: RefCell<Option<&'a A>>,
}

struct C<'a> {
    lookup: RefCell<[Option<&'a B<'a>>; 4]>,
}

struct Holder<'a> {
    c: C<'a>,
    b: B<'a>,
}

fn main() {
    let c = C {
        lookup: RefCell::new([None;4]),
    };

    let b = B {
        ref_a: RefCell::new(None),
    };

    let holder = Holder { c, b };

    holder.c.lookup.borrow_mut()[0] = Some(&holder.b);
}

I would expect this to be fine with heapless::Vec as well. The same problem exists with the heapless::FnvIndexMap which uses heapless::Vec internally.
Can this have something to do with the const initialization here ?
So my question is this intentional/ a trade-off that was deliberately chosen?

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugstatus: blockedBlocked on another issue, or on upstream libraries

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions