Skip to content

Better diagnostics when where clauses need on associated type in impl #92033

Closed
@chubei-oppen

Description

@chubei-oppen

As suggested in #87479, I'm reporting a case where the required bound breaks code.

I was writing a 3D renderer and modeling the surface and swapchain concepts using traits.

A Surface is something you can render to, it should produce a iterator of references to Textures:

struct Texture;

trait Surface {
    type TextureIter<'a>: Iterator<Item = &'a Texture>;

    fn get_texture(&self) -> Self::TextureIter<'_>;
}

A Swapchain produces a reference to a Surface:

trait Swapchain {
    type Surface<'a>: Surface;

    fn get_surface(&self) -> Self::Surface<'_>;
}

Now a Texture itself can be used as a swapchain, producing reference to itself as the Surface.

impl<'s> Surface for &'s Texture {
    type TextureIter<'a> = std::option::IntoIter<&'a Texture>;

    fn get_texture(&self) -> Self::TextureIter<'_> {
        let option: Option<&Texture> = Some(self);
        option.into_iter()
    }
}

impl Swapchain for Texture {
    type Surface<'a> = &'a Texture;

    fn get_surface(&self) -> Self::Surface<'_> {
        self
    }
}

Above code compiles under rustc 1.58.0-nightly (0d1754e8b 2021-11-05).

Now it doesn't with added where Self: 'a bound.

This is a simplified example as Surface and Swapchain have other required methods.

Meta

rustc --version --verbose:

rustc 1.59.0-nightly (efec54529 2021-12-04
Backtrace

<backtrace>
error[E0477]: the type `&'s Texture` does not fulfill the required lifetime
  --> src/main.rs:18:5
   |
18 |     type TextureIter<'a> = std::option::IntoIter<&'a Texture>;
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
note: type must outlive the lifetime `'a` as defined here
  --> src/main.rs:18:22
   |
18 |     type TextureIter<'a> = std::option::IntoIter<&'a Texture>;
   |                      ^^

For more information about this error, try `rustc --explain E0477`.
error: could not compile `rsplayground` due to previous error

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-GATsArea: Generic associated types (GATs)A-diagnosticsArea: Messages for errors, warnings, and lintsC-bugCategory: This is a bug.F-generic_associated_types`#![feature(generic_associated_types)]` a.k.a. GATsGATs-triagedIssues using the `generic_associated_types` feature that have been triaged

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions