Hacker News new | past | comments | ask | show | jobs | submit login

Thanks for this snippet. Didn't think about that.

If I understand correctly that's overly restrictive though. You're limiting the lifetime of list elements to the lifetime of the spine of the list.

What I want is this:

    enum List<T> {
        Nil,
        Cons(T, Box<List<T>>)
    }

    struct IntoIter<T>(List<T>);

    impl<T> IntoIterator for List<T> {
        type Item = T;
        type IntoIter = IntoIter<T>;
        fn into_iter(self) -> Self::IntoIter {
            IntoIter(self)
        }
    }

    impl<T> Iterator for IntoIter<T> {
        type Item = T;
        fn next(&mut self) -> Option<T> {
            match std::mem::replace(&mut self.0, List::Nil) {
                List::Nil => None,
                List::Cons(x, l) => {
                    std::mem::replace(&mut self.0, *l);
                    Some(x)
                }
            }
        }
    }

But without the `replace` calls.

Also, in general I may be working with a data type for which I don't have a value I can conjure out of thin air (like `Nil`). What then?




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: