Other solution than using 'static lifetime

Viewed 150

Here the code:

#[derive(Debug, Eq, PartialEq)]
struct Id(u128);

pub struct IdIter(Box<dyn Iterator<Item= Id>>);

impl IdIter {
    pub fn new<I: Iterator<Item= Id>>(tmpl: I) -> Self {
        Self(Box::new(tmpl))
    }
}

impl Iterator for IdIter {
    type Item = Id;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }
}

pub trait Link {
    fn iter_id(&self) -> IdIter;
}

pub fn links(it: impl Iterator<Item= impl Link>) -> impl Iterator<Item= Id> {
    it.into_iter().flat_map(|l| l.iter_id())
}

#[cfg(test)]
mod test {
    struct X(u128);

    impl super::Link for X {
        fn iter_id(&self) -> super::IdIter {
            super::IdIter(Box::new(Some(super::Id(self.0)).into_iter()))
        }
    }

    #[test]
    fn test_links() {
        let mut v = super::links([X(1234), X(4321)].into_iter());

        assert_eq!(v.next(), Some(super::Id(1234u128)));
        assert_eq!(v.next(), Some(super::Id(4321u128)));
        assert_eq!(v.next(), None);
    }
}

Playground

The compiler suggests the use of 'static lifetime to fix the problem but it's a little excessive.

What i want is offer a trait (here Link) which an iterator of that trait through the links function gives an iterator of Id instances. The trait is used as a marker trait too therefore i can't use another library.

How can i fix the compiler errors ?

2 Answers

Your error can be reduced to the following:

pub struct IdIter(Box<dyn Iterator<Item=()>>);

impl IdIter {
    pub fn new<I: Iterator<Item=()>>(tmpl: I) -> Self {
        Self(Box::new(tmpl))
    }
}

The error is as follows:

error[E0310]: the parameter type `I` may not live long enough
 --> src/lib.rs:5:14
  |
4 |     pub fn new<I: Iterator<Item=()>>(tmpl: I) -> Self {
  |                -- help: consider adding an explicit lifetime bound `I: 'static`...
5 |         Self(Box::new(tmpl))
  |              ^^^^^^^^^^^^^^
  |
note: ...so that the type `I` will meet its required lifetime bounds
 --> src/lib.rs:5:14
  |
5 |         Self(Box::new(tmpl))
  |              ^^^^^^^^^^^^^^

It's not obvious initially, but the error points you in the general direction of what's occurring: Box<dyn Iterator<Item = ()>> in your struct is automatically Box<dyn Iterator<Item = ()> + 'static>, while I may not necessarily be 'static.

The solution is to introduce a new lifetime:

pub struct IdIter<'a>(Box<dyn Iterator<Item = ()> + 'a>);

impl<'a> IdIter<'a> {
    pub fn new<I: Iterator<Item = ()> + 'a>(tmpl: I) -> Self {
        Self(Box::new(tmpl))
    }
}

Playground

It compiles after giving IdIter and explicit lifetime and adjusting several parts of the program. Here's the complete playground example.

#[derive(Debug, Eq, PartialEq)]
pub struct Id(u128);

pub struct IdIter<'a>(Box<dyn Iterator<Item = Id> + 'a>);

impl<'a> IdIter<'a> {
    pub fn new<I: Iterator<Item = Id> + 'a>(tmpl: I) -> Self {
        Self(Box::new(tmpl))
    }
}

impl Iterator for IdIter<'_> {
    type Item = Id;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }
}

pub trait Link {
    fn iter_id(&self) -> IdIter;
}

pub fn links<'a>(it: impl Iterator<Item = &'a (impl Link + 'a)> + 'a) -> impl Iterator<Item = Id> + 'a {
    it.flat_map(Link::iter_id)
}

#[cfg(test)]
mod test {
    struct X(u128);

    impl super::Link for X {
        fn iter_id(&self) -> super::IdIter {
            super::IdIter(Box::new(Some(super::Id(self.0)).into_iter()))
        }
    }

    #[test]
    fn test_links() {
        let mut v = super::links([X(1234), X(4321)].iter());

        assert_eq!(v.next(), Some(super::Id(1234u128)));
        assert_eq!(v.next(), Some(super::Id(4321u128)));
        assert_eq!(v.next(), None);
    }
}
Related