How to allocate arrays on the heap in Rust 1.0? -
there question related rust 0.13 , syntax seems have changed. current documentation understood creating array on heap this:
fn main() { const size: usize = 1024 * 1024; box::new([10.0; size]); }
but when run program following error:
thread '<main>' has overflowed stack
what doing wrong?
the problem array being passed box::new
function argument, means has created first, means has created on stack.
you're asking compiler create 8 megabytes of data on stack: that's what's overflowing it.
the solution not use fixed-size array @ all, vec
. simplest way can think of make vec
of 8 million 10.0
this:
fn main() { const size: usize = 1024 * 1024; let v = vec![10.0; size]; }
or, if 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 perform single heap allocation.
edit: note can subsequently take vec
, turn box<[_]>
using into_boxed_slice
method.
Comments
Post a Comment