Skip to content

Poor labels for anonymous lifetimes in diagnostics #43288

Closed
@jsgf

Description

@jsgf

Given this (incorrect) code:

use std::collections::HashMap;

type MyMap<'a, 'b> = HashMap<&'a str, &'b str>;

fn foo(iter: &mut Iterator<Item=&str>, mut map: MyMap) {
    map.insert(iter.next().unwrap(), "value");
}

fn main() {
}

rustc reports:

   Compiling playground v0.0.1 (file:///playground)
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
 --> src/main.rs:6:28
  |
6 |     map.insert(iter.next().unwrap(), "value");
  |                            ^^^^^^
  |
note: first, the lifetime cannot outlive the anonymous lifetime #2 defined on the function body at 5:1...
 --> src/main.rs:5:1
  |
5 | / fn foo(iter: &mut Iterator<Item=&str>, mut map: MyMap) {
6 | |     map.insert(iter.next().unwrap(), "value");
7 | | }
  | |_^
note: ...so that types are compatible (expected std::option::Option<&str>, found std::option::Option<&str>)
 --> src/main.rs:6:28
  |
6 |     map.insert(iter.next().unwrap(), "value");
  |                            ^^^^^^
note: but, the lifetime must be valid for the anonymous lifetime #3 defined on the function body at 5:1...
 --> src/main.rs:5:1
  |
5 | / fn foo(iter: &mut Iterator<Item=&str>, mut map: MyMap) {
6 | |     map.insert(iter.next().unwrap(), "value");
7 | | }
  | |_^
note: ...so that reference does not outlive borrowed content
 --> src/main.rs:6:16
  |
6 |     map.insert(iter.next().unwrap(), "value");
  |                ^^^^^^^^^^^^^^^^^^^^

error: aborting due to previous error

error: Could not compile `playground`.

The lifetime #1 notation is not very clear or helpful. Assuming it's referring to the lifetimes of the reference parameters, it would be better if it gave them names and used those, along the lines of:

Given:
fn foo<'a, 'b, 'c, 'd>(iter: &'a mut Iterator<Item=&'b str>, mut map: MyMap<'c, 'd>) {

error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
 --> src/main.rs:6:28
  |
6 |     map.insert(iter.next().unwrap(), "value");
  |                            ^^^^^^
  |
note: first, the lifetime cannot outlive the anonymous lifetime 'b defined on the function body at 5:1...

(etc)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-lifetimesArea: Lifetimes / regionsC-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