Iterating with Map Over References

So this is a very simple question, but I am failing at it. I want to use the map function to create an iterator that iterates over the mut references of a vector's elements. I do not want to move the elements into map by value because I want to keep using the vector after iterating.

When I try the following code the compiler complains, that

main.rs(10, 45): data moved here
main.rs(10, 45): move occurs because `c` has type `BigStruct`, which does not implement the `Copy` trait
struct BigStruct(usize);

pub fn main() {
    let mut v = Vec::new();

    for i in 0..16 {
        v.push(BigStruct(i));
    }

    let it = (&mut v).into_iter().map(|&mut c| c.0 + 1);
}

When you type |&mut c|, you are destructuring the value. You're saying: This is a mutable reference to a value I will call c, and I just want the c. So you're actually taking it out of the mutable reference when you do that. You just want |c| c.0 + 1.

It's like when you say if let Some(inner) = option { ..., you are asking for what's inside the option, not the option itself.

2 Likes

Use |c| intead of |&mut c| in your closure parameters (playground).

Using |c| will bind c to the reference that's passed in, while using |&mut c| binds c to the value that the reference refers to.

1 Like

Obligatory shameless self-plug: Patterns Are Not Expressions (Because They're Duals)

6 Likes

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