Vec<T> for T:Default but not Clone

Suppose T implements Default but not Clone. Then, we can not do vec![ T::default(); N ]

instead, we have to do:

let mut ans = Vec::with_capacity(N);
for _ in 0 .. N { ans.push(T::default()); }

Is there a builtin for this ?

You could use resize_with:

pub fn create_vec<T: Default>(size: usize) -> Vec<T> {
    let mut v = vec![];
    v.resize_with(size, T::default);
    v
}
2 Likes

Or (0..size).map(|_| T::default()).collect()

4 Likes

Or even more simply (point-free): iter::repeat_with(T::default).take(size).collect()

4 Likes