Skip to content

Unhelpful diagnostic for sort_by_key lifetime issue #92039

Open
@tornewuff

Description

@tornewuff

Given the following code: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=132fc68312d40c6ed0d878b1d5bdb711

fn parse_filename(file: &std::fs::DirEntry) -> &str {
    todo!()
}

fn foo(mut files: Vec<std::fs::DirEntry>) {
    files.sort_by_key(parse_filename);
}

The current output is:

error[E0308]: mismatched types
 --> src/lib.rs:6:11
  |
6 |     files.sort_by_key(parse_filename);
  |           ^^^^^^^^^^^ one type is more general than the other
  |
  = note: expected associated type `<for<'r> fn(&'r DirEntry) -> &'r str {parse_filename} as FnOnce<(&DirEntry,)>>::Output`
             found associated type `<for<'r> fn(&'r DirEntry) -> &'r str {parse_filename} as FnOnce<(&DirEntry,)>>::Output`

For more information about this error, try `rustc --explain E0308`.

Ideally the output should explain the lifetime issue somehow rather than saying "one type is more general than the other" for two identical types. I understand that the reason why this code doesn't work is as described in https://stackoverflow.com/questions/47121985/why-cant-i-use-a-key-function-that-returns-a-reference-when-sorting-a-vector-wi but this error output wasn't informative :)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-associated-itemsArea: Associated items (types, constants & functions)A-diagnosticsArea: Messages for errors, warnings, and lintsA-lifetimesArea: Lifetimes / regionsD-confusingDiagnostics: Confusing error or lint that should be reworked.D-terseDiagnostics: An error or lint that doesn't give enough information about the problem at hand.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions