Iterator as trait type

Hello,

I'm trying to return an iterator stored in a trait type.

trait Traversable {
    type Result;

    fn traverse(self) -> Self::Result;
}

struct MyStruct<T> {
  field: T
}

impl<T> Traversable for VertexesTraversal<T>
{
    type Result = Box<dyn Iterator<Item = T>>;

    fn traverse(self) -> Self::Result {
        Box::new(
            Vec::new<T>().into_iter()
        )
    }
}

But I'm facing errors related to lifetime and I don't understand why. Note that I used a Box here but it was just as an exemple. If something is more suited then I may use it.

The related error:

error[E0310]: the parameter type `T` may not live long enough
  --> src/lib.rs:16:9
   |
11 |   impl<T> Traversable for MyStruct<T>
   |        - help: consider adding an explicit lifetime bound...: `T: 'static`
...
16 | /         Box::new(
17 | |             Vec::new().into_iter()
18 | |         )
   | |_________^ ...so that the type `std::vec::IntoIter<T>` will meet its required lifetime bounds

This is because a Box<dyn SomeTrait> is short-hand for Box<dyn SomeTrait + 'static>, but if the type T happens to be a type that contains a non-static reference, then the thing you are boxing would not be 'static.

You can fix it like this:

impl<T: 'static> Traversable for VertexesTraversal<T> {
    ...
}

Or don't use a trait object.

impl<T> Traversable for VertexesTraversal<T> {
    type Result = std::vec::IntoIter<T>;

    fn traverse(self) -> Self::Result {
        Vec::<T>::new().into_iter()
    }
}
1 Like

Box imposes an implicit 'static lifetime bound on its argument when used for creating a trait object. You have to specify any non-'static lifetime bounds explicitly in order to get this working: Playground.

trait Traversable<'a> {
    type Result: 'a;

    fn traverse(self) -> Self::Result;
}

struct MyStruct<T> {
  field: T
}

impl<'a, T: 'a> Traversable<'a> for MyStruct<T>
{
    type Result = Box<dyn Iterator<Item = T> + 'a>;

    fn traverse(self) -> Self::Result {
        Box::new(
            Vec::<T>::new().into_iter()
        )
    }
}
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.