Hi, I watched Jonhoo's Crust of Rust on closures today and am a little confused about traits.
Given the following code:
pub fn linear1() -> impl Fn(f64) -> f64 {
|x| x
}
pub fn linear2<F: Fn(f64) -> f64>() -> F {
|x| x
}
pub fn linear3<F>() -> F
where
F: Fn(f64) -> f64,
{
|x| x
}
Only linear1
compiles. linear2
and linear3
fail with the following error:
error[E0308]: mismatched types
--> codag/src/math.rs:42:9
|
41 | pub fn linear2<F: Fn(f64) -> f64>() -> F {
| - this type parameter - expected `F` because of return type
42 | |x| x
| ^^^^^ expected type parameter `F`, found closure
|
= note: expected type parameter `F`
found closure `[closure@codag/src/math.rs:42:9: 42:14]`
= help: every closure has a distinct type and so could not always match the caller-chosen type of parameter `F`
Why don't the last two functions compile? I thought that the impl
syntax was just syntactical sugar for the other two.
I found the following in a reply on this thread:
- In a return type, it’s an existential type that’s guaranteed to satisfy the listed trait bounds, but is otherwise opaque.
but I don't understand it.