Cloned And Copied Turn Borrows Into Owned

copied() duplicates Copy types bit-for-bit from borrowed iterators, while cloned() calls Clone for types like String that own heap data.

RustData Integrity

Code

rustsnippet
23 lines
fn main() {
    // i32 is Copy: copied() bit-copies each &i32 into an i32
    let numbers = vec![3, 1, 4, 1, 5];
    let doubled: Vec<i32> = numbers.iter().copied().map(|n| n * 2).collect();
    println!("doubled: {:?}", doubled);
    // iter() only borrows: numbers stay untouched
    println!("numbers: {:?}", numbers);

    // String is not Copy: copied() fails to compile, cloned() clones each into an owned String
    let words = vec![String::from("alpha"), String::from("beta")];
    let owned: Vec<String> = words.iter().cloned().collect();
    println!("owned: {:?}", owned);

    // Cloned copies are independent: mutating a copy leaves the original alone
    let mut independent = owned;
    independent[0].push_str("!");
    println!("copy: {:?} original: {:?}", independent, words);

    // Slice iteration works the same: &[i32] becomes a stream of i32 via copied()
    let slice: &[i32] = &numbers;
    let sum: i32 = slice.iter().copied().sum();
    println!("sum: {}", sum);
}

How it works

Cloned And Copied Turn Borrows Into Owned is built around the function main.

Applying it

The demo output is labeled (doubled:, numbers:, owned:), so every printed line maps back to its originating operation.

Statements that matter

let doubled: Vec<i32> = numbers.iter().copied().map(|n| n * 2).collect();
let owned: Vec<String> = words.iter().cloned().collect();
let sum: i32 = slice.iter().copied().sum();

Interactive Tools for This Topic

FAQ

What does Cloned And Copied Turn Borrows Into Owned print when run?
Execute the whole file; each printed line is prefixed with a label like `doubled:`, `numbers:`, `owned:`.