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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.