Explain why error occurred and solve it

⚓ Rust    📅 2025-09-16    👤 surdeus    👁️ 1      

surdeus

struct Count {
    data: Vec<u32>
}

struct RefMutCountIter<'a> {
    count: &'a mut Count,
    index: usize,
}

impl Count {


    fn iter_mut(& mut self) -> RefMutCountIter {
        RefMutCountIter {
            count: self,
            index: 0,
        }
    }
}


impl<'a> Iterator for RefMutCountIter<'a>{
    type Item = &'a mut u32;

    fn next(& mut self) -> Option<Self::Item>{
        let result = self.count.data.get_mut(self.index);
        if result.is_some() {
            self.index += 1;
        }
        result
    }
}

fn main() {
    let mut count = Count {
        data: vec![100; 10]
    };

    for i in count.iter_mut() {
        println!("{}", *i);
    }
}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
error: lifetime may not live long enough
  --> src/main.rs:30:9
   |
22 | impl<'a> Iterator for RefMutCountIter<'a>{
   |      -- lifetime `'a` defined here
...
25 |     fn next(& mut self) -> Option<Self::Item>{
   |             - let's call the lifetime of this reference `'1`
...
30 |         result
   |         ^^^^^^ method was supposed to return data with lifetime `'a` but it is returning data with lifetime `'1`

error: could not compile `playground` (bin "playground") due to 1 previous error

7 posts - 3 participants

Read full topic

🏷️ Rust_feed