We have a struct with a LinkedList
:
struct XPipeline {
handlers: LinkedList<XHandler>,
}
XPipeline
is the owner of all XHandler
objects and can access and modify them.
We already have the list of handlers; now we need that each handler could refer to its neighbors in the list. Namely, each handler's method could refer to handler's neighbors, modify them and invoke their methods.
My first thoughts were like this: I provide each handler with prev
and next
fields that will refer to neighbors. By adding a new handler into the list, I initialize these fields with corresponding references. Now I can use these references within all handler's methods. (That would be easy-peasy in C++ with pointers).
The problem is: only one owner (i.e. with modification permission) is allowed. And that owner (of all handlers) is already a XPipeline
object. How could I solve it? Maybe, by employing:
handlers: Rc<RefCell<LinkedList<XHandler>>>
But how exactly?
One of the strategies in Rust for multiple links in data structures is to use a Vec<T>
as the backing storage and then index into it with usize
"pointers".
Your case would look something like:
struct XPipeline {
head: usize,
storage: Vec<Node>,
}
struct Node {
handler: XHandler,
next: Option<usize>,
prev: Option<usize>,
}
The bookkeeping is very similar to the pointers you would use in C++.
Also have a look at this discussion on Reddit for ways to deal with ownership in graph-like structures.
I would also just look for crates that implement double linked lists, skip lists, graphs or similar and take inspiration from there.