rencedm112
rencedm112

Reputation: 587

What does move do for variables that are references?

I have a function that composes multiple functions into a single one:

fn compose<'a, T>(fns: &'a [&dyn Fn(T) -> T]) -> Box<dyn Fn(T) -> T + 'a> {
    Box::new(move |mut x| {
        for f in fns {
            x = f(x);
        }
        x
    })
}

Why do I need to move fns here? If I don't put move, I get the following error:

error[E0373]: closure may outlive the current function, but it borrows `fns`, which is owned by the current function
 --> src/lib.rs:2:14
  |
2 |     Box::new(|mut x| {
  |              ^^^^^^^ may outlive borrowed value `fns`
3 |         for f in fns {
  |                  --- `fns` is borrowed here

I don't get why I need to move the fns into the closure when it's just a reference. What does move actually do here?

Upvotes: 1

Views: 154

Answers (1)

Finomnis
Finomnis

Reputation: 22501

A reference is just a normal variable, like any other variable. If you don't move, your fns inside the closure will be a reference to a reference, which goes out of scope at the end of the function.

Upvotes: 2

Related Questions