rustclonedereferenceownership

Are there differences between .to_owned(), .clone() and dereferencing (*)?


With this code on the rust playground:

fn main() {
    let a = &[1, 2, 3];
    
    let mut o = a.to_owned();
    let mut c = a.clone();
    let mut d = *a;
    
    o[0] = 7;
    c[0] = 8;
    d[0] = 9;
    
    println!("o: {:?}", o);
    println!("c: {:?}", c);
    println!("d: {:?}", d);
    println!("a: {:?}", a);
}

I see:

o: [7, 2, 3]
c: [8, 2, 3]
d: [9, 2, 3]
a: [1, 2, 3]

All three methods clone the contents of a.

Are there any differences?


Solution

  • For a reference to an instance of Copy there is no difference.
    That is because for Copy types:

    1. *ref_to_val returns a bitwise copy of val (and doesn't invalidate old value).
    2. The derived Clone impl. for Copy types will implement .clone() using *.
    3. The blanket ToOwned impl. for Clone types will implement .to_owned() using .clone().

    So it all boils down to bitwise copy.
    This is your case.

    If you want to understand how traits Deref, Clone, ToOwned work for !Copy types, you have to understand their purpose and read type-specific docs.
    I believe String and str types are very representative !Copy types that will help you understand the magic. Eg. str is ToOwned, but not Deref or Clone. Your example won't work for these types.