I want to understand why in Rust, we can't create an array with a non-constant size?
Essentially - the piece of code here looks similar (to me). But with vector I can change the length of the vector but can't do that with array. So, why create this artificial limitation:
fn do_something(a: &mut [usize]) {
for i in 0..a.len() {
println!("{}", a[i]);
}
println!();
}
pub fn main() {
let capacity: usize = 5;
let mut v: Vec<usize> = Vec::with_capacity(capacity);
for i in 0..capacity {
v.push(i);
}
do_something(v.as_mut_slice());
v.push(11);
do_something(v.as_mut_slice());
const CONST_CAPACITY: usize = 5;
let mut arr: [usize; CONST_CAPACITY] = [0; CONST_CAPACITY];
do_something(&mut arr);
}
Is it possible to have stack allocated arrays with the size determined at runtime in Rust? - asks a similar question but to any one searching, it is hard to search answer to this question. Perhaps edit the question title slightly to help increase the visibility while searching (and mark this as dupe) or keep both.