Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I call Vec::with_capacity with an i32?

Tags:

rust

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?

like image 310
anderspitman Avatar asked Feb 19 '15 08:02

anderspitman


1 Answers

Cast to usize.

let n: i32 = 4;
let v = Vec::<i16>::with_capacity(n as usize);
like image 138
DrYap Avatar answered Oct 05 '22 07:10

DrYap