In Rust a trait can only be implemented for a type, not for individual variants of an enum, so unfortunately, Option::<T>::None
may not be Clone
if T
is not.
Possible workarounds:
Vec::from_iter((0..capacity).map(|_| None))
, as suggested by @cafce25.std::iter::repeat_with(|| None).take(capacity).collect::<Vec<_>>()
, as suggested by @vallentin.Vec::resize_with
, since Option<T>
will be Default
, no matter the T
:
let mut foo: Vec<Option<T>> = Vec::with_capacity(capacity);
vec.resize_with(5, Default::default);
vec!
that will expand to one of the above, if you need to use such a declaration many times and want to de-noise the code a bit. However, it's probably best to not do this if you only need to create such a Vec
a small number of times.