Suppose we want to copy data into an array from a slice. The slice could be from another array or a vector. Copy_from_slice
can help here.
With this function, we use range syntax to copy data. The implementation is accelerated and will often perform faster than a for
-loop.
Here we demonstrate the usage of copy_from_slice
in a simple Rust program. We copy a part of the data vector into an array.
vec
macro.copy_from_slice()
function and copy only the first 2 elements from the data array into our empty array.copy_from_slice
invocation must be equal (the starting indexes can be different though).fn main() { // Part 1: The data we wish to copy. let data = vec![10, 20, 30, 40]; // Part 2: The memory we want to copy the data to. let mut empty = [0, 0, 0, 0]; // Part 3: Use copy from slice with slices. empty[0..2].copy_from_slice(&data[0..2]); println!("{:?}", empty); }[10, 20, 0, 0]
HashMap
keysSometimes in Rust we want to quickly look up keys in a HashMap
. We can use copy_from_slice()
to perform part of this task.
HashMap
with 3-element array keys, and str
values. We only add 1 entry.copy_from_slice
function. We fill up the key with 3 elements.get()
and if-let
syntax to access the value from the HashMap
at the key we filled with copy_from_slice
.use std::collections::HashMap; fn main() { // Step 1: Create HashMap with array keys. let mut h = HashMap::new(); h.insert([5, 15, 25], "OK"); // Step 2: Copy data into key with copy from slice. let data = [5, 15, 25, 35, 45]; let mut key = [0, 0, 0]; key.copy_from_slice(&data[0..3]); // Step 3: Access HashMap value with key. if let Some(value) = h.get(&key) { println!("{value}"); } }OK
Much like extend_from_slice()
, copy_from_slice
has optimizations that help it perform faster than a loop. Thus it should be preferred when copying from an array or vector.