How to allocate arrays on the heap in Rust 1.0?

前端 未结 1 1301
离开以前
离开以前 2020-11-27 08:30

There is already a question for this but related to Rust 0.13 and the syntax seems to have changed. From the current documentation I understood that creating an array on the

相关标签:
1条回答
  • 2020-11-27 08:54

    The problem is that the array is being passed to the Box::new function as an argument, which means it has to be created first, which means it has to be created on the stack.

    You're asking the compiler to create 8 megabytes of data on the stack: that's what's overflowing it.

    The solution is to not use a fixed-size array at all, but a Vec. The simplest way I can think of to make a Vec of 8 million 10.0 is this:

    fn main() {
        const SIZE: usize = 1024 * 1024;
        let v = vec![10.0; SIZE];
    }
    

    Or, if for some reason you'd rather use iterators:

    use std::iter::repeat;
    
    fn main() {
        const SIZE: usize = 1024 * 1024;
        let v: Vec<_> = repeat(10.0).take(SIZE).collect();
    }
    

    This should only perform a single heap allocation.

    Note that you can subsequently take a Vec and turn it into a Box<[_]> by using the into_boxed_slice method.

    See also:

    • Performance comparison of a Vec and a boxed slice
    0 讨论(0)
提交回复
热议问题