Loops inside loops and mutable reference on Iterator

⚓ Rust    📅 2026-04-20    👤 surdeus    👁️ 3      

surdeus

Hello,

Consider the following code.

#![allow(unused)]

use std::str::Chars;

use std::iter::Iterator;

struct CharIterator<'a> {
    char_iterator: Chars<'a>
}

impl<'a> CharIterator<'a> {
    fn new(char_iterator: Chars<'a>) -> Self {
        Self {
            char_iterator: char_iterator
        }
    }
}

impl Iterator for CharIterator<'_> {
    type Item = char;

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

fn main() {
    let text = String::from("This is a text to parse. ");
    let mut iterator = CharIterator::new(text.chars());

    for _ in &mut iterator {
        for _ in &mut iterator {
        }
    }
}

Obviously, rustc complain about the fact this code tries to create a mutable reference while another is already in scope. But, this here is totally safe, so my question is : how can make this code working, with the simplicity of the for loop ?

1 post - 1 participant

Read full topic

🏷️ Rust_feed