Home > Mobile >  Vec::chunks borrows data and I can't return chunks
Vec::chunks borrows data and I can't return chunks

Time:01-03

I have a .txt file with some text. For example

a
b
...
z

And I wanna get Vec<Vec<&str>> of chunks with size N or something equal (actually, code below gives me <Vec<&[&str]>> and I don't really see difference. I suppose &[&str] is "borrowed" Vec[&str] wanna google.)

Here is my attempt:

fn read_input()<'a>() -> Vec<&'a[&'a str]> {
    let input = include_str!(r"PATH\input.txt");
    let lines_info = input.lines().collect::<Vec<&'a str>>();
    let chunked_lines_info = lines_info.chunks(7).collect::<Vec<&'a [&'a str]>>();

    chunked_lines_info 
}

Basically, I think I know WHY it is: chunks borrows value from lines_info, but 'lines_info' freed at the end of function but I try to return something that borrows freed data. I tried .clone() lines_info before get chunks (the most dummy way) but it never works.

I tried something (better, I suppose) like this:

fn read_input<'a>() -> Vec<[&'a str; 7]> {
    let input = include_str!(r"PATH\input.txt");
    let info = input.lines().array_chunks::<7>().collect();
    info 
}

But it gives me "unstable library" error.

CodePudding user response:

The problem is that lines_info().chunks() borrows from lines_info and cannot outlive it. You need to collect() the chunks. Also, you can use 'static instead of 'a:

fn read_input() -> Vec<Vec<&'static str>> {
    let input = include_str!(r"PATH\input.txt");
    let lines_info = input.lines().collect::<Vec<_>>();
    let chunked_lines_info = lines_info
        .chunks(7)
        .map(|v| v.iter().copied().collect())
        .collect();

    chunked_lines_info
}
  • Related