简体   繁体   English

为什么我仍然可以使用`move`闭包捕获的变量?

[英]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"): 我编写了一个Rust程序,该程序生成所有小写英文字母(“ 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. 我需要将内部闭包标记为move ,因为否则捕获的a借用寿命不会足够长。 However, I don't understand what this move actually does in this case. 但是,在这种情况下,我不知道move实际上是做什么的。 I can still use a after the closure. 关闭后我仍然可以使用a What does the move actually do here? move实际上在做什么?

What does the move actually do here? move实际上在做什么?

It moves the variable into the closure. 它将变量移到闭包中。

I can still use a after the closure 我仍然可以使用a关闭后

a is a &'static char which implements Copy . a&'static char ,它实现Copy The compiler automatically inserts a copy of the value when you use it after it was moved. 值移动后,编译器会在您使用该值时自动插入该值的副本。

See also: 也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM