When should I add mut to closures?

后端 未结 1 566
有刺的猬
有刺的猬 2020-12-11 15:15
fn main() {
    let mut a = String::from(\"a\");
    let closure = || {
        a.push_str(\"b\");
    };

    closure();
}

This won\'t compile:

相关标签:
1条回答
  • 2020-12-11 15:58

    There are 3 function traits in Rust: Fn, FnMut and FnOnce. Going backward:

    • FnOnce only guarantees that the value can be called once,
    • FnMut only guarantees that the value can be called if it is mutable,
    • Fn guarantees that the value can be called, multiple times, and without being mutable.

    A closure will automatically implement those traits, depending on what it captures and how it uses it. By default, the compiler will pick the least restrictive trait; so favor Fn over FnMut and FnMut over FnOnce.

    In your second case:

    let mut a = String::from("a");
    let closure = || {
        a.push_str("b");
        a
    };
    

    This closure requires being able to return a, which requires FnOnce. It moves a into the capture. If you tried to call your closure a second time, it would fail to compile. If you tried to access a, it would fail to compile too.

    This is why FnOnce is a "last resort" implementation.

    On the other hand your first case:

    let mut a = String::from("a");
    let closure = || {
        a.push_str("b");
    };
    

    At most requires a mutable reference to a, and therefore the capture occurs by mutable reference. Since it captures a mutable reference, the closure implements FnMut, and therefore can only be called if it is itself mutable.

    If you remove mut, in front of a, the compiler will signal to you it needs to borrow a mutably.

    The compiler does not require that closure itself be declared mutably until you attempt to call it; after all you could pass it by value to a function without calling it (yourself), in which case mut would be superfluous.

    0 讨论(0)
提交回复
热议问题