Rust: How to implement a linked list?

I thought I would dive into Rust, introducing some very simple structures and algorithms, I started with a linked list. Turns out it's not that simple. This is my code:

enum List<T> 
{
    Node(T, ~List<T>),
    Nil
}

impl<T> List<T>
{
    fn new(vector: &[T]) -> List<T> { Nil }

    fn add(&mut self, item: T)
    {
        let tail = self;
        loop
        {
            match *tail
            {
                Node(_, ~ref next) => tail = next,
                Nil => break
            }
        }
        *tail = Node(item, ~Nil);
    }
}

This will not compile because the next cannot be assigned to the tail in the conformance statement due to incompatible variability. I know that this can easily be done with the help of pointers collected with garbage, but this kind of strikes the educational goals of the exercise: I would like to know how to do this without the Gc or Rc pointers.

+4
source share
1 answer

, , , . , , ​​ ref mut ref.

, add(), :

fn add(&mut self, item: T) {
    match *self {
        Node(_, ref mut next) => next.add(item),
        Nil => *self = Node(item, ~Nil)
    }
}

, , , - .

+5

All Articles