rust

Rust: double linked list


I'm a beginner in Rust. So the answer will be simple.

I try to write something which can be simplified to a double linked list. In other languages I would use a struct with pointers to the both neighbours. I can iterate through it and ste some data. But how to solve it in rust? I would have two writable references to each node and as far as I know this is not possible.


Solution

  • enter image description here

    Rust ownership rules state that each value can only have one owner at a time. But in doubly linked list each node will have two owners. We use Rc smart pointer

      use std::rc::Rc;
    

    To enable multiple ownership, Rust has a type called Rc. Its name is an abbreviation for reference counting, which keeps track of the number of references to a value to know whether or not a value is still in use. If there are zero references to a value, the value can be cleaned up without any references becoming invalid.

    But the thing is a value owned by an Rc pointer is immutable. it is read-only. You might need to modify each node. that is why you need to use RefCell

    use std::cell::RefCell;
    

    That being said, you can create a doubly linked list with struct in Rust.

    struct List<T>{
        head:Pointer<T>,
        tail:Pointer<T>
    }
    
    struct Node<T>{
        element:T,
        next:Pointer<T>,
        prev:Pointer<T>,
    }
    // you need multiple owners who can mutate the data
    // type is option because last_node.next will be Null
    type Pointer<T>=Option<Rc<RefCell<Node<T>>>>;