liveBook · Manning

Copy_from_slice

As explained in Code Like a Pro in Rust

copy_from_slice is a Rust slice method that copies the elements of one slice into another slice of matching length.

`copy_from_slice` copies elements from a source slice into an equally sized mutable destination slice. Elements must implement `Copy`. Use it when the destination already exists and you want a fast copy of a contiguous region. section 4.2 section 11.2.3

Copy into an initialized destination

```rust let source = vec![1, 2, 3]; let mut target = vec![0; source.len()]; target.copy_from_slice(&source); assert_eq!(target, source); ``` Size the destination to match the source; reserving capacity alone does not give it elements to copy into. section 11.2.3

The standard-library implementation checks the lengths, then calls `ptr::copy_nonoverlapping`, a wrapper around `memcpy`. Exclusive mutable access prevents the slices from overlapping. A release-mode comparison reported roughly 0.025 seconds for pushing 10 million items versus 0.0036 seconds for `copy_from_slice`; that comparison also uses differently prepared destinations, so measure your own workload. section 4.2 section 11.2.3

How Code Like a Pro in Rust covers it

How deep it goes
Shows the `Copy` bound, length check, and `ptr::copy_nonoverlapping` call, without developing a full implementation.
Examples
Compares pushing 10 million integers into a reserved vector with copying into an initialized vector in release mode.
What it assumes
Assumes Rust familiarity while briefly identifying slices as contiguous regions with a length.
What you can do after
Apply it via Rust slices or vectors to copy `Copy` elements into an equally sized destination.
How it connects
Connects slices and vectors to `Copy`, exclusive mutable references, `ptr::copy_nonoverlapping`, and `memcpy`.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Code Like a Pro in Rust. The section links point to the parts of the book it draws on.