0

I have a string that was read from a file. For each line, I would like to split the string and save the split strings to memory as vectors:

use std::io::{BufReader, BufRead};

fn main() {
    let s = r#"line1,line
    line2,line2"#;

    let reader = BufReader::new(s.as_bytes());
    let mut out = Vec::new();

    let iter = reader
        .lines()
        .map(|line| line.unwrap().to_string())
        .collect::<Vec<_>>();

    for x in iter {
        let split = x.split(',').collect::<Vec<_>>();
        out.push(split);
    }
}

Error message

error[E0597]: `x` does not live long enough
  --> src/main.rs:18:6
   |
16 |         let split = x.split(',').collect::<Vec<_>>();
   |                     - borrow occurs here
17 |         out.push(split);
18 |     }
   |      ^ `x` dropped here while still borrowed
19 | }
   | - borrowed value needs to live until here
5
  • 1
    The CSV format is a lot more than splitting on commas, so do you want advice on fixing your borrow error, or on how to parse as CSV with a library? Commented Aug 11, 2017 at 18:53
  • @loganfsmyth I know, If I were using this in production, I would use a crate. Here I am just trying to get some better feeling for this borrowing. Should I delete the CSV tag? Commented Aug 11, 2017 at 18:54
  • 1
    Nice idea trying to put the error message into the code. However, for most experienced Rust programmer, it's much more helpful if you just copy the error message of the compiler verbatim. Would be awesome if you could still do that :) Also: please provide a minimal reproducible example ... you're code is missing the function signature, for example. Commented Aug 11, 2017 at 18:58
  • Hard to decide when this counts as an exact duplicate, but it's the same issue as in stackoverflow.com/questions/33286213/… and stackoverflow.com/questions/34652021/…. Commented Aug 11, 2017 at 19:03
  • 1
    TL;DR from the duplicates: when you iterate over iter, you transfer ownership of the Vec and the strings inside it to the for loop. split returns a reference to the string, but the string will be deallocated ("dropped") at the end of each loop iteration, invalidating any references. Instead of consuming iter during iteration, iterate over references to it. One example Commented Aug 11, 2017 at 19:24

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.