Rust panics with 'capacity overflow' when collecting cycle iterator

Hi everyone,

When I run the following code:

fn main() {
    let array = [7, 1, 2, 3, 4, 5, 6];
    let mut iter_array = array.iter().cycle();
    iter_array.next();
    let vec: Vec<_> = iter_array.collect(); 
}

Rust exits with panic when it tries to collect the iterator into the vector:

❯ cargo run --bin array-rotate-array
    Finished dev [unoptimized + debuginfo] target(s) in 0.00s
     Running `target\debug\array-rotate-array.exe`
thread 'main' panicked at 'capacity overflow', library\alloc\src\raw_vec.rs:525:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
error: process didn't exit successfully: `target\debug\array-rotate-array.exe` (exit code: 101)

I'm not sure what is going on so any guidance would be appreciated. Thanks.

The first line of the docs for cycle is

Repeats an iterator endlessly.

Obviously if you attempt to collect an infinite iterator you're going to run out memory.

If you want to collect the next n elements from the infinite iterator you can use take to limit how many elements are collected

3 Likes

Thanks for your guidance, it makes total sense. I'm still struggling to fully grasp the 'functional programming' way of thinking. :sweat_smile:

Maybe we could help if you told us what you expected an infinite iterator to do when collected into a collection. Since a collection of infinite size is impossible to realize, it is unnatural to expect that it should work.

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.