Search code examples
genericsrustcastingfunction-pointers

Rust: non-primitive cast: `impl Fn()` as `fn()`


The following function

fn ptr_of(f: impl Fn()) -> fn() {
    f as fn()
}

causes this error:

non-primitive cast: `impl Fn()` as `fn()`

What am I missing?

Context

What I'm trying to do is actually slightly different as seen below, however the above example is the simplest form of the problem.

trait FnExt {
    fn do_smth_with_ptr(&self);
}

impl<T: Fn()> FnExt for T {
    fn do_smth_with_ptr(&self) {
        let ptr: fn() = self as fn(); //error here
        todo!();
    }
}

fn example() {
    example2.do_smth_with_ptr();
}

fn example2() {};

I was expecting this to work, because trying ptr_of with a specific function like the following example works:

fn test() {}

let ptr = test as fn();

Solution

  • Fn() is implemented by all closures that don't accept arguments and return unit, but the cast "Closure as Function pointer" is "only [valid] for closures that do not capture (close over) any local variables" as you can look up in the table of valid casts

    See also: Why does passing a closure to function which accepts a function pointer not work?