Iterator design pattern for mutable reference

⚓ Rust    📅 2025-10-17    👤 surdeus    👁️ 1      

surdeus

I'm having problem with implementation iterator design pattern for mutable reference. Note that analog code works fine for ordinary reference but doesn't for mutable given in the following code. There is an error regarding lifetimes you may find it in the line comment in the implementation of the next() method. I've read other similar topics but failed to find solution. Is this a bug?

#[derive(Debug)]
struct MyCollection {
    data: Vec<i32>,
}

struct MyCollectionRefMutIterator<'a> {
    current_index: usize,
    data: &'a mut Vec<i32>,
}

impl <'a> Iterator for MyCollectionRefMutIterator<'a> {
    type Item = &'a mut i32;

    fn next(&mut self) -> Option<Self::Item> {
        if self.current_index < self.data.len() {
            let item = &mut self.data[self.current_index];
            self.current_index += 1;
            Some(item) // Error! lifetime may not live long enough
                       // method was supposed to return data with lifetime `'a` but it is returning data with lifetime `'1`
        } else {
            None
        }
    }
}

impl <'a> IntoIterator for &'a mut MyCollection {
    type Item = &'a mut i32;
    type IntoIter = MyCollectionRefMutIterator<'a>;

    fn into_iter(self) -> Self::IntoIter {
        MyCollectionRefMutIterator {
            current_index: 0,
            data: &mut self.data,
        }
    }
}

fn main() {}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn mut_reference_collection() {
        let mut collection = MyCollection { data: vec![1, 2, 3] };
        for item in &mut collection {
            *item += 10;
            println!("{}", item);
        }
        assert_eq!(vec![11, 12, 13], collection.data);
    }
}

7 posts - 6 participants

Read full topic

🏷️ Rust_feed