How to understand this Rust function that returns another function?

Viewed 749

While reading about Rust, I ran into an example function that takes a number and returns a function that adds that number to another number.

fn higher_order_fn_return<'a>(step_value: &'a i32) -> Box<Fn(i32) -> i32 + 'a> {
    Box::new(move |x: i32| x + step_value)
}

There are so many Rust-specific mechanisms here I can't make sense of it. I'm sure some of it has to do with lifetime management but the reasons why this must be written this way eludes me. A few questions:

  • Why is step_value passed in as a reference?
  • Why is the function being returned boxed?
  • How to interpret the unconventional way to write a function type (as Fn(i32) -> i32 + 'a) ?
  • Why is 'a written as a generic (<'a>) but "added" in the return type (+ 'a) ?
  • What is the meaning of move and what is being moved here?
2 Answers
Related