Iterating over a slice's values instead of references in Rust?

You can remove the reference by destructuring in the pattern:

//  |
//  v
for &var in slice {
    other_fn(var);
}

However, this only works for Copy-types! If you have a type that doesn't implement Copy but does implement Clone, you could use the cloned() iterator adapter; see Chris Emerson's answer for more information.


In some cases you can iterate directly on values if you can consume the iterable, e.g. using Vec::into_iter().

With slices, you can use cloned or copied on the iterator:

fn main() {
    let v = vec![1, 2, 3];
    let slice = &v[..];
    for u in slice.iter().cloned() {
        let u: usize = u; // prove it's really usize, not &usize
        println!("{}", u);
    }
}

This relies on the item implementing Clone or Copy, but if it doesn't you probably do want references after all.

Tags:

Iterator

Rust