copy_from_slice Examples
This page was last reviewed on Feb 24, 2023.
Dot Net Perls
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.
Vec extend from slice
First example. 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.
Part 1 This is the data we are copying into our array. The vector here has 4 elements and is created with the vec macro.
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.
Step 2 We copy into our "key" array by using the copy_from_slice function. We fill up the key with 3 elements.
Step 3 We use 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}"); } }
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.
This page was last updated on Feb 24, 2023 (new).
© 2007-2024 Sam Allen.