lifetime/IntoIterator question

I am confused about a lifetime issue. I have a struct which i have coded up iterators for.


/// NodePath IntoIterator, iterates over owned Nodes in NodePath
pub struct NodePathIntoIterator<'a> {
    nodepath: &'a mut NodePath<'a>,
    index: usize,
}

impl<'a> Iterator for NodePathIntoIterator<'a> {
    type Item = Node;

    fn next(&mut self) -> Option<Node> {
        if self.index >= self.nodepath.len() {
            return None;
        }

        let idx = self.nodepath.nodes[self.index];
        let result = self.nodepath.graph[idx].clone();
        self.index += 1;
        Some(result)
    }
}

I have a function on NodePath called into_iter() which does this:

pub fn into_iter(&'a mut self) -> NodePathIntoIterator<'a> {
        NodePathIntoIterator{nodepath: self, index: 0}
    }

and i have a test that is failing in a way that doesn't make sense to me...

    #[test]
    fn into_iter_works() {
        let graph = build_graph();
        let mut np = NodePath::new(&graph);
        for x in graph.node_indices() {
            np.push(x).unwrap();
        }
        
        for x in np.into_iter() {
            println!("{:?}", x);
        }

        assert!(np.count() == 0);
    }
}

And finally here is the error:

 Compiling jsp v0.14.0 (/Users/jonathangerber/src/rust/jobsyspolice)
error[E0502]: cannot borrow `np` as immutable because it is also borrowed as mutable
   --> src/nodepath.rs:468:17
    |
462 |         let iter = np.into_iter();
    |                    -- mutable borrow occurs here
...
468 |         assert!(np.count() == 0);
    |                 ^^
    |                 |
    |                 immutable borrow occurs here
    |                 mutable borrow later used here

error: aborting due to previous error

The only borrow I have is in the NodePathIntoIterator which should go out of scope after the loop, so why am i getting this? Shouldn't this be handled by NLL? Also, this even fails if I put the loop in its own scope... What am i missing here?

yikes! am i trying to mix IntoIter and IterMut here? looks like i am. my bad. i guess i should be moving NodePath int NodePathIntoIter, not referencing it... never mind.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.