Skip to content

Weird HRTB behavior with associated types #99548

Open
@ArtBlnd

Description

@ArtBlnd

I've trying compile this code.

// This does not compiles
fn create_baa_in_the_foo1() {
    create_baa(Foo(()));
}

// This compiles
fn create_baa_in_the_foo2() {
    Baa(Foo(()));
}

struct Baa<A>(A);
fn create_baa<A, B>(foo: A) -> Baa<A>
where
    A: for<'a> FooTrait<'a, Output = B>,
{
    Baa(foo)
}

trait FooTrait<'a> {
    type Output;
    fn output(&'a self) -> Self::Output;
}

struct Foo(());
impl<'a> FooTrait<'a> for Foo {
    type Output = &'a ();

    fn output(&'a self) -> Self::Output {
        &self.0
    }
}

Everyone knows the lifetime of the Foo(()) is general enough but it emits error.

error: implementation of `FooTrait` is not general enough
  |
2 |     create_baa(Foo(()));
  |     ^^^^^^^^^ implementation of `FooTrait` is not general enough
  |
  = note: `Foo` must implement `FooTrait<'0>`, for any lifetime `'0`...
  = note: ...but it actually implements `FooTrait<'1>`, for some specific lifetime `'1`

If we remove Output = B and its generic type B it works fine.

struct Baa<A>(A);
fn create_baa<A>(foo: A) -> Baa<A>
where
    A: for<'a> FooTrait<'a>,
{
    Baa(foo)
}

or in other way, moving references associate type to method signature. it also works.

trait FooTrait<'a> {
    type Output;
    fn output(&'a self) -> &'a Self::Output;
}

struct Foo(());
impl<'a> FooTrait<'a> for Foo {
    type Output = ();

    fn output(&'a self) -> &'a Self::Output {
        &self.0
    }
}

I guess at least this code should have same lifetime behavior as first one.
Am I doing wrong with something or this is something the bug related to #70263?

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-associated-itemsArea: Associated items (types, constants & functions)A-higher-rankedArea: Higher-ranked things (e.g., lifetimes, types, trait bounds aka HRTBs)A-lifetimesArea: Lifetimes / regionsT-typesRelevant to the types 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