(I made this post on reddit and received a suggestion to repost it here.)
I noticed yesterday a curious property of type inference in Rust. The following does not work:
Box::new(|| 1) as Box<Fn() -> u32>
Rust first infers the closure return type as i32, creates a box of that, then attempts to convert it into a trait object with incorrect return type u32.
However, the following does work:
fn box_fn<F, R>(f: F) -> Box<Fn() -> R> where F: Fn() -> R + 'static {
Box::new(f) as Box<Fn() -> R>
}
fn requires_u32(f: Box<Fn() -> u32>) -> u32 {
f()
}
requires_u32(box_fn(|| 1));
Now the very generic closure wrapper needs to get its types straight first, which it does by figuring the calling expression needs a Fn() -> u32, matching the R type as such. Then the lambda is created within this explicitly u32 return value requiring context, making it all work out.
Could such inferrence be extended to type conversions such as in the first bit of code? Such that the conversion would be evaluated first as requiring something convertable into a specific type, which could be used to guide type inferrence on the left side?