Reputation: 15502
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:
Fn
for each corresponding fn
type?Fn
to fn
I'm asking more about mental model than about concrete implementation.
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
Reputation: 2079
It is the former (the implementations are produced by the compiler). From the documentation.
all safe function pointers implement
Fn
,FnMut
, andFnOnce
. 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