Arrays and dynamic allocation

I'm testing the capability of rust to decide if I should convert to that as my goto language.

I have at this moment read the whole book from front to back and done some simple implementation to get accustom to the syntax and type system (not that big a deal comming from SML and F#)

I though have a implementation related question.

Why did they not make it possible to make allocation of an array dynamic? i.e. making it possible to give initiate an array with size n where n is computed at run time. I understand that this will lead to a minor runtime penalty, since we need to compute that size at runtime, but still this is a marginal runtime penalty.

Yes I know that there is the 'Vec' type, but this is resizable which can leads to even more runtime penalty, and give less clear intention of the code, when read by other programmers.

To sum it up why isn't it possible to do something like
fn darr(item : i32, n : i32) {
let arr = [item; n];
println!("sum is {}",arr.iter().sum());
}

it is possible to make a dynamic sized stack frame under the assumption that the size is given at runtime before allocation, with little overheath (calculation of the size).

There is a merged RFC for this, meaning that it will eventually be supported in Rust. It just isn't the top priority at the moment, because it can be worked around fairly easily.

1 Like

And if you don't need to put the array on stack, for now there's Box<[T]>, which is like Vec, but doesn't have any overhead of resizability.

1 Like

I'm still not sure if we do really needs VLA for Rust. C is the only language I know which supports it, even C++, which supports virtually every paradigms human invented, doesn't supports VLA.

VLA is hard topic. It prevents lots of compiler optimizations which are based on the fixed stack offset. But furthermore, call stack is fairly limited place to put large data. On windows it's 1MB by default, and it's sort of common to blow up the stack without VLA, even without the recursive function.

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.