Understanding i32 type, clone func and copy trait

This is a pretty simple doubt that I'm making only for rust understanding reasons.

    let mut n = 0;
    let x = n;
    n = n + 1;
    println!("{}, {}", n, x);

we know we can still interact with n after "let x = n" because we have the copy trait. But then, what's the difference between that and:

    let mut n = 0;
    let x = n.clone();
    n = n + 1;
    println!("{}, {}", n, x);

?
and why is the clone func even usable with i32 type?
Thank you if anybody knows it!

Clone is a supertrait of Copy, so you have to implement Clone if you implement Copy. That way, all Copy types can satisfy a T: Clone bound.

The clone should just make a copy in that case, and does for all std types. (But the compiler doesn't enforce this and you can't rely on it for safety in a general sense.)

Notionally at least, the .clone() is an additional function call to optimize away (but I wouldn't worry about it (but-but I wouldn't intentionally clone when I could copy, either) ).

2 Likes

Though (of course!) there is default warn clippy lint: clippy::non_canonical_clone_impl

3 Likes

Here's a link to some official documentation on the topic.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.