'How do I allocate space for elements in vector for type T?

fn test<T>(arr: &mut [T]) {

    let vector=vec![] //what can I do here so that I have vector as vec with same size as arr and of type T.

}

fn main() {
    let xs = vec![1, 2, 3, 4, 5, 6];
    test(&mut xs);
}

Is there any solution if I enforce T to have Default trait? I should be able to randomly access the created vector, not push serially.



Solution 1:[1]

There's a few ways to do this. If you can enforce that T: Default you can use resize_with

fn test<T: Default>(arr: &mut [T]) {
    let v: Vec<T> = Vec::new();
    v.resize_with(arr.len(), Default::default);
}

Otherwise, you can enforce that T: Clone and use resize with a provided initial value for the elements:

fn test<T: Clone>(arr: &mut [T], initial: T) {
    let v: Vec<T> = Vec::new();
    v.resize(arr.len(), initial);
}

Solution 2:[2]

Use the with_capacity method

fn test<T>(arr: &mut [T]) {
    let vector : Vec<T> =  Vec::with_capacity(arr.len());
    ...
}

Mind that it doesn't allocate the elements, it just makes the underlying buffer big enough for N elements without extra re-allocations.

I should be able to randomly access the created vector, not push serially"

Another easy way allocating the elements if they are Clone, is simply use the vec! macro:

fn test<T: Clone>(arr: &mut [T], item: T) {
    let vector : Vec<T> =  vec![item; arr.len()];
    ...
}

Solution 3:[3]

The vec macro can accept a two-arguments form where the first one is an element that will repeated, and the second is the number of repeated elements.

It would look like something like this:

fn test<T: Clone+Default>(arr: &mut [T]) {
    let vector = vec![T::default(); arr.len()];
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 cdhowie
Solution 2
Solution 3