Skip to content

Trait objects do not work with generic associated types #81823

Open
@matthewjasper

Description

I tried this code:

#![feature(generic_associated_types)]

trait StreamingIterator {
    type Item<'a> where Self: 'a;
    fn size_hint(&self) -> (usize, Option<usize>);
    // Uncommenting makes `StreamingIterator` not object safe
//    fn next(&mut self) -> Self::Item<'_>;
}

fn min_size(x: &mut dyn for<'a> StreamingIterator<Item<'a> = &'a i32>) -> usize {
    x.size_hint().0
}

I expected to see this happen: either code compiles or an error message is emitted for any use of a trait object with generic associated types

Instead, this happened: code produces inconsistent error messages:

error[E0038]: the trait `StreamingIterator` cannot be made into an object
  --> <source>:18:16
   |
18 | fn min_size(x: &mut dyn for<'a> StreamingIterator<Item<'a> = &'a i32>) -> usize {
   |                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `StreamingIterator` cannot be made into an object
   |
   = help: consider moving `next` to another trait
note: for a trait to be "object safe" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit <https://doc.rust-lang.org/reference/items/traits.html#object-safety>
  --> <source>:15:26
   |
11 | trait StreamingIterator {
   |       ----------------- this trait cannot be made into an object...
...
15 |    fn next(&mut self) -> Self::Item<'_>;
   |                          ^^^^^^^^^^^^^^ ...because method `next` references the `Self` type in its return type

error: aborting due to previous error
error: generic associated types in trait objects are not supported yet
  --> <source>:19:7
   |
19 |     x.size_hint().0
   |       ^^^^^^^^^

error: aborting due to previous error

Compiler returned: 1

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    A-GATsArea: Generic associated types (GATs)A-trait-objectsArea: trait objects, vtable layoutC-bugCategory: This is a bug.GATs-triagedIssues using the `generic_associated_types` feature that have been triagedrequires-nightlyThis issue requires a nightly compiler in some way.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions