# Why must closure variable be mut

**URL:** <https://users.rust-lang.org/t/why-must-closure-variable-be-mut/53583>\
**Category:** help\
**Created:** [January 2, 2021, 2:58pm UTC](https://users.rust-lang.org/t/why-must-closure-variable-be-mut/53583 "2021-01-02T14:58:15Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![mvolkmann](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/mvolkmann/32/18387_2.png) [@mvolkmann](https://users.rust-lang.org/u/mvolkmann)\
**Post date:** [January 2, 2021, 2:58pm UTC](https://users.rust-lang.org/t/why-must-closure-variable-be-mut/53583/1 "2021-01-02T14:58:16Z")

</div>

Why does `inner` need to be `mut` in this example?  
I never modify the `inner` variable which is assigned a closure.  
Is it because any closure that modifies a variable in its environment must be `mut`?

```rust
fn main() {
    let mut a = String::new();
    let mut inner = | | {
        let b = String::from("test");
        a = b; // Moves ownership from b to a.
    };
    inner();
    println!("{}", a);
}

```

([Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=2ba3a4cea5c0ac0f78bf5b01f78676e9))

Output:

```rust
test

```

Errors:

```rust
   Compiling playground v0.0.1 (/playground)
    Finished dev [unoptimized + debuginfo] target(s) in 0.85s
     Running `target/debug/playground`

```

---

<div class="post-metadata">

**Author:** ![cole-miller](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/cole-miller/32/16722_2.png) [@cole-miller](https://users.rust-lang.org/u/cole-miller)\
**Post date:** [January 2, 2021, 3:15pm UTC](https://users.rust-lang.org/t/why-must-closure-variable-be-mut/53583/2 "2021-01-02T15:15:26Z")

</div>

There's no error in the compiler output you posted, perhaps you meant to remove the `mut` first?

Anyway, yes, you have the right idea. See the signature for the [`call_mut`](https://doc.rust-lang.org/std/ops/trait.FnMut.html#tymethod.call_mut) method of `FnMut`, which is implemented by closures that modify their environment.

[This post](https://rustyyato.github.io/rust/syntactic/sugar/2019/01/17/Closures-Magic-Functions.html) by @RustyYato may be of interest.

---

<div class="post-metadata">

**Author:** ![vitalyd](https://avatars.discourse-cdn.com/v4/letter/v/edb3f5/32.png) [@vitalyd](https://users.rust-lang.org/u/vitalyd)\
**Post date:** [January 2, 2021, 3:23pm UTC](https://users.rust-lang.org/t/why-must-closure-variable-be-mut/53583/3 "2021-01-02T15:23:04Z")

</div>

Since the closure doesn't move `a` into itself, it's capturing a mutable reference in order to perform `a = b` assignment. You can imagine the compiler generates a closure struct similar in spirit to:

```rust
struct Closure<'a>(&'a mut String); // captured `a` mutable reference

impl FnMut<()> for Closure<'_> {
     fn call_mut(&mut self, _: ()) {
         let b = String::from("test");
         *self.0 = b;
     }
}

```

---

<div class="post-metadata">

**Author:** ![steffahn](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/steffahn/32/47569_2.png) [@steffahn](https://users.rust-lang.org/u/steffahn)\
**Post date:** [January 2, 2021, 5:19pm UTC](https://users.rust-lang.org/t/why-must-closure-variable-be-mut/53583/4 "2021-01-02T17:19:50Z")

</div>

To add to the previous commenters, here’s how the desugaring of the closure call works:

In the code

```rust
fn main() {
    let mut a = String::new();
    let mut inner = || {
        let b = String::from("test");
        a = b;
    };
    inner();
    println!("{}", a);
}

```

the compiler first deduces that the closure mutates `a`, so it includes a mutable reference to `a` in the closure. (This will e.g. mean that you cannot access `a` anymore until after the last call to `inner`.) Then it also sees that the closure does not move out of any of it’s captured variable. This means that it can implement `FnMut` but it cannot implement `Fn`.

The call to `inner()` thus gets desugared using the `FnMut` interface. You can think of the desugaring of such a call to use `Fn` interface whenever possible. (Not possible for this closure.) Then, as a fallback use `FnMut` interface (works works for this closure). And if the closure had not implemented `FnMut` it would’ve fallen back to using the `FnOnce` interface. In this case this means that we get

```rust
// needs nightly for explicitly mentioning
// the `Fn*` traits
#![feature(fn_traits)]
fn main() {
    let mut a = String::new();
    let mut inner = || {
        let b = String::from("test");
        a = b;
    };
    inner.call_mut(());
    println!("{}", a);
}

```

([playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=a5bb4320b2321c7a2097ea4fa441e028))

As the previous commenters have shown, `call_mut` takes a `&mut self` argument, hence this desugars further to

```rust
// needs nightly for explicitly mentioning
// the `Fn*` traits
#![feature(fn_traits)]
fn main() {
    let mut a = String::new();
    let mut inner = || {
        let b = String::from("test");
        a = b;
    };
    FnMut::call_mut(&mut inner, ());
    println!("{}", a);
}

```

([playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=c1faa0bebed550da123c7ec9cbb65d98))

This `&mut inner` reference being created is the reason why we need the `mut` when declaring `inner`.

---

<div class="post-metadata">

**Author:** ![system](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/system/32/51372_2.png) [@system](https://users.rust-lang.org/u/system)\
**Post date:** [April 2, 2021, 5:19pm UTC](https://users.rust-lang.org/t/why-must-closure-variable-be-mut/53583/5 "2021-04-02T17:19:59Z")

</div>

Closed on April 2, 2021, 5:19pm UTC

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.
