Vec::with_capacity
does not affect the length of the vector, only the capacity; the new vector will still have length 0. The difference is that it not need to reallocate until its length reaches the requested capacity.
The method clone_from_slice
is actually a method of slices ([T]
) not Vec<T>
, but Vec
s can be dereferenced as slices, so these methods are still callable. Even though clone_from_slice
will overwrite all of the items in the destination slice, it still needs a valid slice with fully initialized items.
There would be a lot of complications if the slice contained a mixture of initialized and uninitialized items. Initialized items may need to be dropped, while uninitialized items really must not be dropped. The maintainers of the std
library could have solved this by adding an extra parameter to say where the boundary of initialized and uninitialized values is, but that would have made it much harder to use: if you were to pass in the wrong value for the boundary it would trigger Undefined Behaviour, so the method would also have to be marked unsafe
.