rust - How to iterate through a collection but only a required number of items? - Stack Overflow

admin2025-04-17  6

What is the 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;
        }
    }
}

What is the 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;
        }
    }
}
Share Improve this question edited Jan 31 at 19:36 kmdreko 61.8k6 gold badges95 silver badges163 bronze badges asked Jan 31 at 13:35 HarryHarry 3,2581 gold badge24 silver badges46 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 3

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);
}
转载请注明原文地址:http://www.anycun.com/QandA/1744859626a88630.html