Skip to content

Diagnostics doesn't provide proper explaination as to where type annotations should be added #48089

Closed
@shingtaklam1324

Description

@shingtaklam1324

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()

Playground

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-type-systemArea: Type systemC-enhancementCategory: An issue proposing an enhancement or a PR with one.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions