I am reading multiple lines from stdin
.
I want store those lines into a Vec<String>
and then make use of it with references.
Here a simplified code template:
let mut pretty_line: &str;
let mut lines: Vec<String> = Vec::new();
for i in 0..lines_number as usize {
let line = // read line
lines.push(line);
if is_pretty_line(&line) {
pretty_line = &line;
}
}
Since line
would be dropped at the end of the loop I thought of storing it into a Vec to be sure it still exists. But I now end up with borrowing issues because value is moved when lines.push(line);
I thought of :
if is_pretty_line(&lines[i]) {
pretty_line = &lines[i];
}
But not possible either because there is a mutable borrow when pushing to the Vec.
How can I solve this ?
Something interesting if I remove the lines.push(line);
there is no more compilation error even though I am assigning a reference to a String that will be dropped after :pretty_line = &line;
How is that possible ?
Full code :
use std::io;
fn main() {
let mut input_line = String::new();
io::stdin().read_line(&mut input_line).unwrap();
let lines_number = input_line.trim().parse::<i32>().unwrap();
let mut pretty_line: &str;
let lines: Vec<String> = Vec::new();
for _i in 0..lines_number as usize {
let mut line = String::new();
io::stdin().read_line(&mut line).unwrap();
let line = input_line.trim().parse::<String>().unwrap();
lines.push(line);
if is_pretty_line(&line) {
pretty_line = &line;
}
}
}
fn is_pretty_line(line: &str) -> bool {
return true;
}