For loop can't access mutable variable declared outside

Hi all,

I'm attempting to implement a linked list as part of the rust exercism track. I'm getting stuck on something that should be simple: implementing From trait:

impl<'a, T: Clone> From<&'a [T]> for SimpleLinkedList<T> {
    fn from(item: &[T]) -> Self {
        let mut out: SimpleLinkedList<T>;
        for i in item.iter() {
            out.push(i); 
         //^^^ use of possibly uninitialized `out`
        }
        out
    }
}

Why can't the for loop 'see' out? Please forgive the naiveness, I'm very much a beginner (and my head seriously hurts).

Further, if there is a better way to implement this?

Mark

The error says "use of possibly uninitialized" it doesn't say "I can't access variable declared outside".

This line doesn't actually allocate a new linked list, it just decleares that "out" is of that type:

let mut out: SimpleLinkedList<T>;

So you need to create the linked list before pushing things inside it.

1 Like

So simple... thanks!

1 Like