Struct field which points to another field in the same struct

I have a struct like this:

pub struct BinaryHeap<'a, T> {
    elements: VecDeque<T>,
    kind: HeapKind,
    element_indices: HashMap<&'a T, usize>

The Hashmap element_indices is present to keep track of the indices of the elements stored in vector elements. I know that the borrow checker doesn't allow self referential fields. I want to know what other options I have to achieve this? (I really don't want to clone the element just to keep track of its index in the vector.)

Other option for me is to use an Rc<T> pointer and clone the Rc<T> pointer and store that inside the Hashmap, but then my API would become clumsy. Extracting the elements from the heap would then return Rc<T> instead of the original T (Perhaps there is a way to convert from Rc<T> to T ?, I haven't seen that anywhere :confused: )


There is Rc::try_unwrap, which should be fine after you've removed from both places. You'd have to use Arc instead if you want this type to be usable with threads.

You could instead dip a little lower into hashbrown::raw::RawTable like indexmap does, where you'd just store the index in the table, and only your elements would hold an actual T.

1 Like

Thank you so much! Rust community is the best :smiley:
I think I'll go with the hashbrown::raw::RawTable approach, might as well learn something new.