Can somebody suggest an idiomatic way of iterating through the elements of a collection only required number of times. This is my code
fn main() {
let list = vec![1, 3, 5, 7, 9, 11, 11, 11, 11, 13, 15, 17, 19];
let mut count = 10;
let mut itr = list.iter();
while let Some(x) = itr.next() {
if count > 0 {
count -= 1;
print!("{}, ", x);
} else {
break;
}
}
}
You're looking for take()
:
let list = vec![1, 3, 5, 7, 9, 11, 11, 11, 11, 13, 15, 17, 19];
for x in list.iter().take(10) {
print!("{}, ", x);
}