I have a function which allocates a vector on the stack. This code doesn't work:
fn my_func(n: i32) {
let mut v = Vec::with_capacity(n);
}
The compiler says n
needs to be a usize
. I suppose that makes sense from a type safety point of view, but I need to use n
in other calculations where an i32
is called for. What's the proper way to handle this?
Cast to usize.
let n: i32 = 4;
let v = Vec::<i16>::with_capacity(n as usize);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With