Home 10. cloned vs copied
Post
Cancel

10. cloned vs copied

Rust provides built-in methods to copy or clone elements when using an iterator.

Eg.

1
let nums: Vec<u32> = nums1.iter().chain(&nums2).copied().collect();

What’s the difference? and when is it useful?

You may have done something like this:

1
let nums: Vec<u32> = nums1.iter().chain(&nums2).map(|x| *x).collect();

but instead, use copied.

1
let nums: Vec<u32> = nums1.iter().chain(&nums2).copied().collect();

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let nums = vec![1,2,3,4];
let nums2 = vec![5,6,7,8];

// doiing it manually by copying
// let all_nums: Vec<u32> = nums.iter().chain(&nums2).map(|x| *x).collect();

// doiing it manually by cloneing
// let all_nums: Vec<u32> = nums.iter().chain(&nums2).map(|x| x.clone()).collect();

// but why not just use provided functionality ??!
let all_nums: Vec<u32> = nums.iter().chain(&nums2).copied().collect();

// or cloned if copy it is not an option
//let all_nums: Vec<u32> = nums.iter().chain(&nums2).cloned().collect();

 assert_eq!(all_nums, vec![1,2,3,4,5,6,7,8]);

Difference between cloned and copied?

Same reasoning aplies as for Copy and Clone traits. Use copied to avoid to accidentally cloing iterator elements. Use copied when possible.

This post is licensed under CC BY 4.0 by the author.