Search code examples
rustiteratorcollect

set a the capacity of a vector when collecting elements


I am working on a project where I need to repeatedly collect a known number of elements from a buffer into a vector, my current code is:

let mut info: Vec<i32> = buffer.trim().split(" ").collect()

However, as I know that I will receive 2 elements I would like to be able to set the capacity of the vector, something like:

let mut info: Vec<i32>::with_capacity(2) = buffer.trim().split(" ").collect()

Solution

  • Create the vector using with_capacity() and then use .extend() to fill it from an iterator:

    let mut info = Vec::with_capacity(2);
    info.extend(buffer.trim().split(" "));