What is the type for |x| move |y| x + y?

Viewed 87

What is the type for

let plus:Plus = |x| move |y| x + y;

Obviously,

type Plus = fn(isize) -> fn(isize) -> isize;

won't work since the last part is not a function pointer but a closure.

1 Answers

The type is impl Fn(isize) -> (impl Fn(isize) -> isize). It can be coerced to fn(isize) -> (impl Fn(isize) -> isize), because the outer closure does not capture.

However, you cannot express this type in today's Rust. With the nightly feature type_alias_impl_trait, you can break it into two types:

#![feature(type_alias_impl_trait)]

type Adder = impl Fn(isize) -> isize;
type Plus = fn(isize) -> Adder;
let plus: Plus = |x| move |y| x + y;

Playground.

Or you can box it:

type Plus = fn(isize) -> Box<dyn Fn(isize) -> isize>;
let plus: Plus = |x| Box::new(move |y| x + y);

Playground.

Related