Why is the value moved into the closure here rather than borrowed?

前端 未结 1 388
后悔当初
后悔当初 2021-01-12 07:58

The Error Handling chapter of the Rust Book contains an example on how to use the combinators of Option and Result. A file is read and through appl

相关标签:
1条回答
  • 2021-01-12 08:46

    I thought that not marking the closure with move would borrow any referenced value by default,

    Not quite. The compiler does a bit of inspection on the code within the closure body and tracks how the closed-over variables are used.

    When the compiler sees that a method is called on a variable, then it looks to see what type the receiver is (self, &self, &mut self). When a variable is used as a parameter, the compiler also tracks if it is by value, reference, or mutable reference. Whatever the most restrictive requirement is will be what is used by default.

    Occasionally, this analysis is not complete enough — even though the variable is only used as a reference, we intend for the closure to own the variable. This usually occurs when returning a closure or handing it off to another thread.

    In this case, the variable is returned from the closure, which must mean that it is used by value. Thus the variable will be moved into the closure automatically.


    Occasionally the move keyword is too big of a hammer as it moves all of the referenced variables in. Sometimes you may want to just force one variable to be moved in but not others. In that case, the best solution I know of is to make an explicit reference and move the reference in:

    fn main() {
        let a = 1;
        let b = 2;
    
        {
            let b = &b;
            needs_to_own_a(move || a_function(a, b));
        }
    }
    
    0 讨论(0)
提交回复
热议问题