lennoff
lennoff

Reputation: 302

flat_map on Chars causes borrow checker error

I'm trying to generate a sequence like this: 1,2,3,4,5,6,7,8,9,1,0,1,1,1,2...

fn main() {
    let iter = (1..).flat_map(|j| j.to_string().chars());
    for i in iter {
        println!("{}", i);
    }
}

This does not work, because j.to_string() goes out of scope I believe (but why?)

p040.rs:2:35: 2:48 error: borrowed value does not live long enough
p040.rs:2     let iter = (1..).flat_map(|j| j.to_string().chars());
                                            ^~~~~~~~~~~~~
p040.rs:2:58: 6:2 note: reference must be valid for the block suffix following statement 0 at 2:57...
p040.rs:2     let iter = (1..).flat_map(|j| j.to_string().chars());
p040.rs:3     for i in iter {
p040.rs:4         println!("{}", i);
p040.rs:5     }
p040.rs:6 }
p040.rs:2:35: 2:56 note: ...but borrowed value is only valid for the block at 2:34
p040.rs:2     let iter = (1..).flat_map(|j| j.to_string().chars());
                                            ^~~~~~~~~~~~~~~~~~~~~

How could I solve this compiler error?

Upvotes: 1

Views: 98

Answers (2)

malbarbo
malbarbo

Reputation: 11177

One problem with the solution that uses collect is that it keeps allocating strings and vectors. If you need a implementation that does the minimum allocation, you can implement your own iterator:

#[derive(Default)]
struct NumChars {
    num: usize,
    num_str: Vec<u8>,
    next_index: usize,
}

impl Iterator for NumChars {
    type Item = char;

    fn next(&mut self) -> Option<char> {
        use std::io::Write;
        if self.next_index >= self.num_str.len() {
            self.next_index = 0;
            self.num += 1;
            self.num_str.clear();
            write!(&mut self.num_str, "{}", self.num).expect("write failed");
        }

        let index = self.next_index;
        self.next_index += 1;
        Some(self.num_str[index] as char)
    }
}

fn main() {
    assert_eq!(
        vec!['1', '2', '3', '4', '5', '6', '7', '8', '9', '1', '0', '1', '1'],
        NumChars::default().take(13).collect::<Vec<_>>()
    );
}

Upvotes: 2

mcarton
mcarton

Reputation: 30061

Iterators are lazy and can only live as long as their iteratee lives. j.to_string() is temporary and only lives inside the closure, hence the closure cannot return j.to_string().chars(). A simple solution would be to collect the characters before returning:

fn main() {
    let iter = (1..).flat_map(|j| j.to_string().chars().collect::<Vec<_>>());
    for i in iter {
        println!("{}", i);
    }
}

Upvotes: 2

Related Questions