Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In Rust, what is the type for |x| move |y| x + y?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading