Trait objects do not work with generic associated types · Issue #81823 · rust-lang/rust (original) (raw)

I tried this code:

#![feature(generic_associated_types)]

trait StreamingIterator { type Item<'a> where Self: 'a; fn size_hint(&self) -> (usize, Option); // 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>🔞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