5

I have a recursive type which doesn't implement copy

struct Node {
    board: Board,
    children: Option<Vec<Node>>,
}

I have a Vector of these nodes, I want to call a method on each, and then pass them on to another function.

fn foo() {
    let mut nodes: Vec<Node> = get_nodes();
    for i in 0..nodes.len() {
        nodes[i].grow();
    }
    pick_node(nodes);
}

This works, but frustratingly

fn foo() {
    let nodes: Vec<Node> = get_nodes();
    for mut node in nodes {
        node.grow();
    }
    pick_node(nodes);
}

causes an error because "nodes moved due to this implicit call to .into_iter()"

Is there a version of for _ in _ that just gets me references to each member of the vector in turn, without moving or copying, like I get when I use a range like in the first version? It's an issue that comes up a lot for me, and it's been hard to find an answer for some reason. Like Clippy says, the iterator is probably faster, and clearer, and just seems idiomatic.

1
  • You can take a reference there Commented May 13, 2022 at 2:59

1 Answer 1

10

I believe the methods you're looking for are iter and/or iter_mut. So your code will look like the following:

for node in nodes.iter_mut() {
    node.grow();
}

Alternatively, &Vec<T> and &mut Vec<T> both have IntoIterator implementations which return the iterator provided by iter or iter_mut respectively. So the following is also equivalent to the above:

for node in &mut nodes {
    node.grow();
}

Edit

All of the above is correct, just to add a little more clarification:

for pattern in iterable {
    /* body */
}

essentially just desugars to the following:

let mut iter = IntoIterator::into_iter(iterable);
loop {
    match iter.next() {
        Some(pattern) => { /* body */ },
        None => break,
    }
}

into_iter requires an owned self, so that's why your vector is moved when it's substituted in the place of iterable. Ownership of the vector is transferred to its into_iter function. On the other hand, when you put &vec or &mut vec in the place of iterable, it's the references which are copied/moved, leaving the original vector in place.

4
  • 1
    I think this is something the docs should do a better of making clear: in a for loop, iterating over something by value is preferable to calling into_iter() on it, by reference ... iter() (when it's defined), and by mutable reference ... iter_mut() (when it's defined). You only need the _iter_() methods if you want to call additional Iterator methods on the result; "plain" iteration is preferable in for loops. Commented May 13, 2022 at 3:13
  • so iter() and iter_mut() are "plain" ... whereas ... into_iter() is an _iter_() method, and better to avoid unless you need it? Just trying to clarify. Commented May 13, 2022 at 4:07
  • 1
    No to clarify what BallpointBen was talking about, if you just need to iterate by reference do for x in &vec instead of for x in vec.iter(), and similarly use for x in &mut vec for mutable references or for x in vec for owned values. This syntax is just more ergonomic. You only need the iter methods if you want to chain them, for example, for (index, thing) in vec.iter().enumerate().
    – Ian S.
    Commented May 13, 2022 at 7:02
  • 1
    While it isn't a hard rule, the preferred style amongst the Rust community is to use & and &mut over .iter() and .iter_mut() when possible (there is even a clippy lint for that!). Use explicit iter() only for iterator transformations ((&v).into_iter().map() looks really bad). Commented May 15, 2022 at 2:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.