Skip to content

Error in trait solving #80982

Open
Open
@b-naber

Description

@b-naber

Related to #78113. In the following example the trait system cannot resolve the trait object A in Box<dyn A + 'a> to Foo, even though Foo implements A:

#![feature(generic_associated_types)]

trait A {}

struct Foo {}

impl A for Foo {}

impl<'a> A for &'a Box<dyn A + 'a> {}

trait X {
  type T<'a> : A;
}

struct B {}

impl X for B {
  type T<'a> = &'a Box<dyn A + 'a>;
}

impl B {
  fn foo<'a>(&self, arg : &'a Box<Foo>) -> <Self as X>::T<'a> {
    arg
  }

}

fn main() {}

This yields the error:

error[E0308]: mismatched types
  --> /Users/bn/Documents/Rust/rust_error_samples/gat_type_alias_lifetime.rs:23:5
   |
23 |     arg
   |     ^^^ expected trait object `dyn A`, found struct `Foo`
   |
   = note: expected reference `&'a Box<(dyn A + 'a)>`
              found reference `&'a Box<Foo>`

error: aborting due to previous error; 1 warning emitted

If we don't provide a lifetime bound in the implementation of A for &'a Box<dyn A> (impl<'a> A for &'a Box<dyn A>) then we get an additional lifetime error since this trait impl is resolved to impl<'a> A for &'a Box<dyn A + 'static>, resulting in two errors:

error[E0308]: mismatched types
  --> /Users/bn/Documents/Rust/rust_error_samples/gat_type_alias_lifetime.rs:18:3
   |
18 |   type T<'a> = &'a Box<dyn A + 'a>;
   |   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lifetime mismatch
   |
   = note: expected trait `A`
              found trait `A`
note: the lifetime `'a` as defined on the associated item at 18:10...
  --> /Users/bn/Documents/Rust/rust_error_samples/gat_type_alias_lifetime.rs:18:10
   |
18 |   type T<'a> = &'a Box<dyn A + 'a>;
   |          ^^
   = note: ...does not necessarily outlive the static lifetime

error[E0308]: mismatched types
  --> /Users/bn/Documents/Rust/rust_error_samples/gat_type_alias_lifetime.rs:23:5
   |
23 |     arg
   |     ^^^ expected trait object `dyn A`, found struct `Foo`
   |
   = note: expected reference `&'a Box<(dyn A + 'a)>`
              found reference `&'a Box<Foo>`

error: aborting due to 2 previous errors; 1 warning emitted

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsD-confusingDiagnostics: Confusing error or lint that should be reworked.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