0

I have the following code

pub fn new(src_objects: &[Arc<dyn Hitable>], time0: f32, time1: f32) -> Self {
    let object_span = src_objects.len();
    let mut objects = Vec::with_capacity(object_span);
    objects.clone_from_slice(src_objects);
    ...
}

On running this code, the code panics with a message "destination and source slices have different lengths". I ran the same code but replacing clone_fom_slice with extend_from_slice, but I wanted to understand what clone_from_slice is doing here that fails

1 Answers1

1

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 Vecs 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.

Peter Hall
  • 53,120
  • 14
  • 139
  • 204