Skip to content

Returning Self with incorrect lifetime assumsion #105923

Closed as not planned
Closed as not planned
@earthengine

Description

@earthengine

I tried this code:

trait Foo {
    type Gat<'a>: Foo + 'a where Self: 'a;
    fn foo<'a>() -> Self::Gat<'a> where Self: Sized + 'a;
}
enum Bar<'a> {
    Baz(&'a ())
}

impl<'b> Foo for Bar<'b> {
    type Gat<'a> = Bar<'a> where Self: 'a;
    fn foo<'a>() -> Bar<'a> {
        //Worked: 
        //Bar::Baz(&())
        //error: lifetime may not live long enough
        //= help: consider adding the following bound: `'b: 'a`
        Self::Baz(&())
    }
}

Playground

I expected to see it to compile since it worked if replacing Self with the actual enum name.

Instead, it reports error

error: lifetime may not live long enough
  --> src/lib.rs:16:9
   |
9  | impl<'b> Foo for Bar<'b> {
   |      -- lifetime `'b` defined here
10 |     type Gat<'a> = Bar<'a> where Self: 'a;
11 |     fn foo<'a>() -> Bar<'a> {
   |            -- lifetime `'a` defined here
...
16 |         Self::Baz(&())
   |         ^^^^^^^^^^^^^^ associated function was supposed to return data with lifetime `'a` but it is returning data with lifetime `'b`
   |
   = help: consider adding the following bound: `'b: 'a`

error: could not compile `playground` due to previous error

Meta

This is replicated in ALL channels in the playground.

It may or may not related to the newly stabilized GAT feature, but this example surely requires to use this feature.

It might be justifiable to reject the code given; but it would need a good reason and being well documented. To general users like me, the assumption is that Self in this context should be equivalent to the enum name, without any lifetime assumptions.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-bugCategory: This is a bug.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions