Skip to content

Invalid double reference returned from closure should get suggestion #144992

@cyrgani

Description

@cyrgani

Code

use std::collections::HashMap;
fn main() {
    let data = HashMap::<String, u8>::new();
    let mut ordered = data.iter().collect::<Vec<_>>();
    ordered.sort_by_key(|(field, _)| field);
}

Current output

error: lifetime may not live long enough
 --> src/main.rs:5:38
  |
5 |     ordered.sort_by_key(|(field, _)| field);
  |                          ----------- ^^^^^ returning this value requires that `'1` must outlive `'2`
  |                          |         |
  |                          |         return type of closure is &'2 &String
  |                          has type `&'1 (&String, &u8)`

Desired output

error: lifetime may not live long enough
 --> src/main.rs:5:38
  |
5 |     ordered.sort_by_key(|(field, _)| field);
  |                          ----------- ^^^^^ returning this value requires that `'1` must outlive `'2`
  |                          |         |
  |                          |         return type of closure is &'2 &String
  |                          has type `&'1 (&String, &u8)`
help: `field` is a double reference, dereference it first: *field

Rationale and extra context

The fix for this code is to just dereference field once, but the diagnostic gives no suggestion.

Other cases

Rust Version

1.91.0-nightly

(2025-08-05 ec7c02612527d185c379)

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsD-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