Max Heiber
Max Heiber

Reputation: 15502

What enables a function trait type to be used where an fn type is expected?

What enables a function trait type (std::ops::Fn) to be used where an fn type (e.g. closure, function definition, fn pointer type) is expected?

fn take_closure<F: Fn(u32) -> u32>(_f: F) {}

fn id(x: u32) -> u32 {
    x
}

fn main() {
    take_closure(id);
}

Is it:

I'm asking more about mental model than about concrete implementation.

Edit

updated the example, previously the example showed conversion the other way. Sorry about that. I created a separate question to ask about conversion the other way: What enables a closure type to be used where a function pointer type to be used in Rust?

Upvotes: 0

Views: 284

Answers (1)

Teymour
Teymour

Reputation: 2079

It is the former (the implementations are produced by the compiler). From the documentation.

all safe function pointers implement Fn, FnMut, and FnOnce. This works because these traits are specially known to the compiler.

I sometimes think of this as fn is a Fn which does not capture anything from the environment.

Upvotes: 4

Related Questions