Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
929 views
in Technique[技术] by (71.8m points)

rust - When should I add mut to closures?

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

    closure();
}

This won't compile:

error[E0596]: cannot borrow immutable local variable `closure` as mutable
 --> src/main.rs:7:5
  |
3 |     let closure = || {
  |         ------- consider changing this to `mut closure`
...
7 |     closure();
  |     ^^^^^^^ cannot borrow mutably

If I return a in the closure without adding mut, it can be compiled:

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

    closure();
}

This confuses me a lot. It seems like when I call closure(), closure will be borrowed if something is mutable inside it. Why won't it be borrowed when I return a?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...