closure return type inference doesn't consider coercions
The title is a guess as to why this code doesn't compile:
fn foo(x: Option<&mut i32>) -> Option<&i32> {
x.map(|x| x)
}
error[E0308]: mismatched types
--> src/main.rs:3:5
|
3 | x.map(|x| x)
| ^^^^^^^^^^^^ types differ in mutability
|
= note: expected type `std::option::Option<&i32>`
found type `std::option::Option<&mut i32>`
while given the tiniest of type hints, it does:
fn foo(x: Option<&mut i32>) -> Option<&i32> {
x.map(|x| -> &_ { x })
}
It seems that the type inference sees the closure returning &mut i32 but doesn't consider that that coerces to the desired type. Is this unintended and/or fixable?
This is probably intended, coercions only happen when there is no type inference needed to resolve the coercion, so
&mut _to&_is fine, because all&mut Tcan be coerced to&T, but in your example the argument type and the return type of the closure are inferred (even if it is simple inference), so coercion won't kick in. Although, we could special case simple cases like this, it doesn't seem to come up often enough to be worth the complexity in the compiler.RustyYato at 2019-04-25 05:11:26