Copy from slice. 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.
Part 2 This is the "empty" array of 4 elements we want to populate with copied data.
Part 3 Here we invoke the copy_from_slice() function and copy only the first 2 elements from the data array into our empty array.
Important The length of the 2 ranges in the 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 keys. Sometimes in Rust we want to quickly look up keys in a HashMap. We can use copy_from_slice() to perform part of this task.
Step 1 We create a HashMap with 3-element array keys, and str values. We only add 1 entry.
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
Final notes. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.