Zizheng Tai
Zizheng Tai

Reputation: 6646

Why can I still use a variable captured by a `move` closure?

I wrote a Rust program that generates all the two-letter permutations of lower-case English letters ("aa", "ab", ..., "zy", "zz"):

fn main() {
    static ASCII_LOWER: [char; 26] = [
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
        'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
    ];

    let x: Vec<_> = ASCII_LOWER.iter().flat_map(|a| {
        let result = ASCII_LOWER.iter().map(move |b| {
            format!("{}{}", a, b)
        });

        dbg!(a);  // <--- How can `a` still be used?

        result
    }).collect();

    dbg!(x);
}

I need to mark the inner closure as move, because otherwise the captured borrow of a doesn't live long enough. However, I don't understand what this move actually does in this case. I can still use a after the closure. What does the move actually do here?

Upvotes: 3

Views: 111

Answers (1)

Shepmaster
Shepmaster

Reputation: 431949

What does the move actually do here?

It moves the variable into the closure.

I can still use a after the closure

a is a &'static char which implements Copy. The compiler automatically inserts a copy of the value when you use it after it was moved.

See also:

Upvotes: 8

Related Questions