What does it mean that iter is mut?

let iter = some_collection.iter();
iter.next();//Won't compile???

Does it mean that in order to "advance" iterator I have to declare it as mutable?

Iterators typically look something like this:

struct SliceIterator<'a, T> {
    slice: &'a [T],
    index: usize,
}

Since the next method modifies the index field, you need mutable access.

(the real slice iterator is slightly different, but this example is better for getting the point across)

1 Like

OK, I get it. So basically:

let iter = some_collection.iter()

is more or less pointless? Or am I missing something?

Well it depends. It could make sense to do if the expression is long. You don't need mut if you give away ownership of the iterator to something else, even if the new owner proceeds to modify it.

1 Like

Would you mind giving an example?

For loops take ownership of the iterator you give them.

fn main() {
    let a = vec![1, 2, 3];
    
    let iter = a.iter();
    for val in iter {
        println!("{}", val);
    }
}
1 Like

Would you call it an idiomatic use of rust?
But wait, what about:

for x in &iter {
        println!("{}", x);
    }

If the iterator expression is very long or multiple lines, I think it's fine.

fn main() {
    let a = vec![1, 2, 3];
    
    let iter = a.iter()
        .filter(|&a| *a == 2)
        .copied();
    
    for val in iter {
        println!("{}", val);
    }
}
1 Like

If you give a for loop a reference, it takes ownership of the reference, not the original value.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.