Collect deep copy values

Is there a way to collect primitive values, instead of references? For example, I have the following function:

fn test() -> Vec<i32> {
    let items: Vec<i32> = (0..10).collect();
    let items: Vec<&i32> = items.iter().collect();
    let items: Vec<&&i32> = items.iter().collect();
    let items: Vec<&&&i32> = items.iter().collect();
    let items: Vec<&&&&i32> = items.iter().collect();

    // I would like to write something like:
    //     items.iter().deep_copied().collect()
    items.iter().map(|&&&&&x| x).collect()
}

I would like to write something like items.iter().deep_copied().collect(), instead of destructuring the variable again and again. Is there any idiomatic way to do this?

I doubt people would call this "idiomatic", but you can make auto-deref do the work for you:

pub fn test() -> Vec<i32> {
    let items: Vec<i32> = (0..10).collect();
    let items: Vec<&i32> = items.iter().collect();
    let items: Vec<&&i32> = items.iter().collect();
    let items: Vec<&&&i32> = items.iter().collect();
    let items: Vec<&&&&i32> = items.iter().collect();

    use std::ops::Add;
    items.iter().map(|x| x.add(0)).collect()
}
1 Like

The idiomatic way is to avoid && in the first place, since it doesn't add any functionality, only overhead. So keep calling .copied() earlier.

    let items: Vec<i32> = (0..10).collect();
    let items: Vec<&i32> = items.iter().collect();
    let items: Vec<&i32> = items.iter().copied().collect();
    let items: Vec<&i32> = items.iter().copied().collect();
    let items: Vec<&i32> = items.iter().copied().collect();
1 Like

Even better if you use into_iter instead, if you aren't going to use the Vec again.

3 Likes
    items.iter().map(|x| i32::clone(x)).collect()
2 Likes