Stuck here: error[E0700]: hidden type for `impl Iterator<Item = u8>` captures lifetime that does not appear in bounds

Hello everyone,

I'm (relatively) new to rust and am trying to build small toy programs to learn the language. I got stuck with an error and I made a minimal representation of that code in the playground. I'd really appreciate it if someone could point me in the right direction.

#[derive(Copy, Clone)]
struct Inner <'a> {
    v: &'a Vec<u8>,
}

struct IterForInner <'a> {
    s: Inner <'a>,
}

struct Outer <'a> {
    v: Vec<Inner<'a>>,
}

impl <'a> Iterator for IterForInner <'a> {
    type Item = u8;
    
    fn next(&mut self) -> Option<Self::Item> {
        None
    }
}

impl <'a> IterForInner <'a> {
    fn new(s: Inner<'a>) -> Self {
        IterForInner {
            s,
        }
    }
}

impl <'a> Outer <'a> {
    pub fn get_iter(&self) -> impl Iterator<Item = u8> {
        IterForInner::new(self.v[0])
    }
}

fn main() {
    println!("Hello, world!");
}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
error[E0700]: hidden type for `impl Iterator<Item = u8>` captures lifetime that does not appear in bounds
  --> src/main.rs:32:9
   |
30 | impl <'a> Outer <'a> {
   |       -- hidden type `IterForInner<'a>` captures the lifetime `'a` as defined here
31 |     pub fn get_iter(&self) -> impl Iterator<Item = u8> {
32 |         IterForInner::new(self.v[0])
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

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

The return type has to borrow part of self for 'a but the opaque return type doesn't currently indicate that. You just need to add a lifetime bound to the opaque return type

impl<'a> Outer<'a> {
    pub fn get_iter(&self) -> impl Iterator<Item = u8> + 'a {
        IterForInner::new(self.v[0])
    }
}

Though you could of course also fix it by just naming the type directly

pub fn get_iter(&self) -> IterForInner<'a>
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.