Skip to content

lifetime error mentions implemented trait instead of the associated type and the mismatched type. #59865

Open
@rodrimati1992

Description

@rodrimati1992

In this reddit thread a user commented on their confusion with an error message.

The problem is that the lifetime error for this code mentions Iterator twice in the error message instead the types whose lifetimes don't match.

The code that triggers the bug:

use std::marker::PhantomData;

struct AnIterator<'a> {
    first: String,
    _marker:PhantomData<&'a str>
}

impl<'a> Iterator for AnIterator<'a> {
    type Item = &'a str;

    fn next<'b>(&'b mut self) -> Option<Self::Item> {
        Some(self.first.as_str())
    }
}

The error message:

   Compiling playground v0.0.1 (/playground)
error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
  --> src/lib.rs:12:25
   |
12 |         Some(self.first.as_str())
   |                         ^^^^^^
   |
note: first, the lifetime cannot outlive the lifetime 'b as defined on the method body at 11:13...
  --> src/lib.rs:11:13
   |
11 |     fn next<'b>(&'b mut self) -> Option<Self::Item> {
   |             ^^
note: ...so that reference does not outlive borrowed content
  --> src/lib.rs:12:14
   |
12 |         Some(self.first.as_str())
   |              ^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on the impl at 8:6...
  --> src/lib.rs:8:6
   |
8  | impl<'a> Iterator for AnIterator<'a> {
   |      ^^
   = note: ...so that the types are compatible:
           expected std::iter::Iterator
              found std::iter::Iterator

error: aborting due to previous error

For more information about this error, try `rustc --explain E0495`.
error: Could not compile `playground`.

Here in the last note,instead of saying expected std::iter::Iterator found std::iter::Iterator,
it should be expected &'a str found &'b str.

It prints the correct error message if I change ->Option<Self::Item> to ->Option<&'a str>.

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.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