rust-lang / rust-lang/rust

Invalid double reference returned from closure should get suggestion

Open
#144,992 1 comment 0 reactions 1 assignee View on GitHub

@xizheyin is already working on this.

Since Aug 11, 2025.

A-diagnostics D-terse T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.