anderspitman
anderspitman

Reputation: 10530

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

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?

Upvotes: 5

Views: 3830

Answers (1)

DrYap
DrYap

Reputation: 6647

Cast to usize.

let n: i32 = 4;
let v = Vec::<i16>::with_capacity(n as usize);

Upvotes: 8

Related Questions