Home
Rust
copy_from_slice Examples
Updated 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.
vec
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.
HashMap
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.
if
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.
This page was last updated on Feb 24, 2023 (new).
Home
Changes
© 2007-2025 Sam Allen