Skip to content

Mismatched lifetime in trait function declaration is not detected #48812

@glandium

Description

@glandium

Consider the following code:

pub trait FromStr<'a>: Sized {
    type Err;
    fn from_str(s: &'a str) -> Result<Self, Self::Err>;
}

struct Foo<'a>(&'a str);

impl<'a> FromStr<'a> for Foo<'a> {
    type Err = ();
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Foo(s))
    }
}

The compiler errors out failing to infer an appropriate lifetime:


error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'a` due to conflicting requirements
  --> src/main.rs:11:12
   |
11 |         Ok(Foo(s))
   |            ^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 10:5...
  --> src/main.rs:10:5
   |
10 | /     fn from_str(s: &str) -> Result<Self, Self::Err> {
11 | |         Ok(Foo(s))
12 | |     }
   | |_____^
note: ...so that reference does not outlive borrowed content
  --> src/main.rs:11:16
   |
11 |         Ok(Foo(s))
   |                ^
note: but, the lifetime must be valid for the lifetime 'a as defined on the impl at 8:1...
  --> src/main.rs:8:1
   |
8  | impl<'a> FromStr<'a> for Foo<'a> {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   = note: ...so that the expression is assignable:
           expected std::result::Result<Foo<'a>, _>
              found std::result::Result<Foo<'_>, _>

But the most immediate error is that the declaration of from_str doesn't match the trait definition, missing the lifetime bound on &str to match the lifetime associated with the trait.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`C-enhancementCategory: An issue proposing an enhancement or a PR with one.D-papercutDiagnostics: An error or lint that needs small tweaks.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.fixed-by-NLLBugs fixed, but only when NLL is enabled.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions