Closed
Description
Code
fn main() {
let lst: [([i32; 10], bool); 10] = [([0; 10], false); 10];
lst.sort_by_key(|&(v, _)| v.iter().sum());
println!("{:?}", lst);
}
Current Error message
This fails compilation (on purpose), and the error message is as below
error[E0282]: type annotations needed
--> src/main.rs:3:9
|
3 | lst.sort_by_key(|&(v, _)| v.iter().sum());
| ^^^^^^^^^^^ cannot infer type for `B`
error: aborting due to previous error
error: Could not compile `playground`.
Problem
The current error message isn't helpful by producing a message with the type B
, which can be confusing to users, (it comes from te type signature of fn sort_by_key<B, F>(&mut self, _: F) where B: Ord, F: FnMut(&T) -> B
as estebank
points out).As well as that, the positions of the arrows implies that the error comes from .sort_by_key()
, when in fact it comes from the need for type annotations for .sum()
.
Proposed solution
error[E0282]: type annotations needed
--> src/main.rs:3:9
|
3 | lst.sort_by_key(|&(v, _)| v.iter().sum());
| ^^^^^^^^^^^^^^ cannot infer type for `B`
error: aborting due to previous error
error: Could not compile `playground`.
The proposed change would be to point to the inside of the function, which would (in my opinion) be clearer to the user that the type annotations are needed inside the function, not with .sort_by_key()