Rust Reference ยท Collections
Rust copy_from_slice, fill and to_vec
Reference for copying and filling slices in Rust: copy_from_slice, clone_from_slice, copy_within, fill, fill_with, to_vec and length-mismatch panics.
A slice cannot be assigned with = (its size is unknown to the compiler), so Rust provides methods that overwrite its contents. copy_from_slice(src) copies the bytes of a Copy slice into this one. clone_from_slice(src) does the same for Clone types. fill(value) writes the same value into every position. to_vec() goes the other way: it makes a fresh Vec<T> from a borrowed slice by cloning.
The destination and source must have exactly the same length for the copy methods; there is no silent truncation.
let mut buf = [0u8; 4]; buf.copy_from_slice(&[1, 2, 3, 4]); buf[..2].fill(9); let owned: Vec<u8> = buf.to_vec();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
impl<T> [T] { pub fn copy_from_slice(&mut self, src: &[T]) where T: Copy; pub fn clone_from_slice(&mut self, src: &[T]) where T: Clone; pub fn copy_within<R: RangeBounds<usize>>(&mut self, src: R, dest: usize) where T: Copy; pub fn fill(&mut self, value: T) where T: Clone; pub fn fill_with<F: FnMut() -> T>(&mut self, f: F); pub fn to_vec(&self) -> Vec<T> where T: Clone; pub fn repeat(&self, n: usize) -> Vec<T> where T: Copy; }
| Name | Description |
|---|---|
src |
The source slice (or, for copy_within, the range inside self to copy). |
dest |
For copy_within, the index where the copied block starts. |
value |
Cloned into every slot; the last slot receives the original value without a clone. |
f |
Called once per slot to produce each new value. |
Returns: the copy and fill methods return nothing; to_vec and repeat return a new Vec<T>.
Panics: copy_from_slice and clone_from_slice panic when the lengths differ. copy_within panics if the source range or the destination block does not fit inside the slice.
Usage notes
- Lengths must match exactly. Slice both sides to the same length first:
dst[..n].copy_from_slice(&src[..n]). copy_from_sliceis amemcpy. It is the fastest way to move plain data, and it is whyCopyis required. Useclone_from_sliceforString,Vecand other owning types.- Overlap rules: two different slices cannot overlap, because one is
&mutand the other&. For overlapping moves within one buffer usecopy_within, which behaves likememmove. fillclones the value into all but the last slot. For expensive or non-Clonevalues usefill_withwith a closure (for example|| Vec::new()).- Arrays are
Copyif their elements are, solet b = a;copies an array outright; slices need the methods here. to_vecvsclone(): cloning a&[T]copies the reference, not the data.to_vec()copies the elements.slice.to_owned()is equivalent.- Zeroing a buffer is
buf.fill(0). For secrets that must not be optimized away, use a dedicated crate; the optimizer may remove dead writes. - Converting back to arrays:
<[T; N]>::try_from(slice)returns an array copy when the length matches, as in[T; N] arrays.
Related
[T] slices,[T; N] arrays,Vec<T>,Clone,Copy,extend, append, split_off- Lessons: Slices, Copy and Clone