Geert
1
This is my sample extracted from my first bigger project
fn main() {
let lines: Vec<String> = vec![
"123456".to_string(),
"234567".to_string(),
"345678".to_string()
];
let skip_lines: Vec<&String> = lines.iter().skip(1).collect();
report2(skip_lines);
}
fn report2(lines: Vec<&String>) {
while let Some(&l) = lines.iter().next() {
println!("{}", l);
}
}
This prints out always the same line 234567.
What did I do wrong?
2e71828
2
Every time you call lines.iter()
, it creates a new iterator that starts at the beginning. Call it only once and store it in a variable instead:
fn report2(lines: Vec<&String>) {
let mut iter = lines.iter();
while let Some(&l) = iter.next() {
println!("{}", l);
}
}
Or use a for
loop, which only evaluates its argument once:
fn report2(lines: Vec<&String>) {
for &line in lines.iter() {
println!("{}", l);
}
}
3 Likes
system
Closed
3
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.