Is this function possible to create in Rust?

Viewed 75
fn foo(f: fn(u32) -> u32) -> fn(u32, u32) -> u32 {
    unimplemented!()
}

A function that takes a function pointer as an argument, and returns a function pointer that calls the original function, ignoring the extra parameter.

Something similar in concept to the following, ignoring that it doesn't compile:

fn foo(f: fn(u32) -> u32) -> fn(u32, u32) -> u32 {
    |x, _| f(x)
}
1 Answers

Unfortunately, this is not possible. Functions do not have states, so each time you call foo, a brand new function has to be generated that calls f internally, which is apparently not possible.

If you are willing to relax the return type, you can return an impl Fn(u32, u32) -> u32:

fn foo(f: fn(u32) -> u32) -> impl Fn(u32, u32) -> u32 {
    move |x, _| f(x)
}

fn main() {
    let new_f = foo(|x| x);
    assert_eq!(new_f(1, 2), 1);
}
Related