Cannot call clone automatically

By "original value" I mean a, not b.

a = b; always does the same thing for all types, Copy or not. It copies the bits just like in C.

Again, a = b; is equally expensive whether or not the type is Copy. There may be a second order effect where making a type Copy allows the programmer to do things that inhibit the compiler's ability to optimize away that cost, but implementing Copy itself has no effect on code generation at all.

I actually believe that @yushang's observation that there is a difference between physical copy and logical copy is key to understanding Copy. People (including myself earlier in this thread) tend to use the word "copy" without specifying which they mean. Which one you mean is usually deducible from context, but only to people who already understand the dichotomy, so it's easy to talk past each other. Here's my attempt at explaining it:

  • A physical copy is the process of taking bits and replicating them in a new place. In Rust this is also called move.
  • A logical copy is the process of taking a value and turning it into two new values. In Rust this is also called clone.

Rust does implicit physical copies (moves) all the time. a = b; is a move, which is a copy of the bits from b into a. Returning things and passing things as arguments to functions are also examples of moves, which are copies. Each move, which is a copy, might be compiled to a memcpy, or a single instruction, or no code at all.

At first glance, it seems Rust never does implicit logical copies. You always have to ask for one by calling clone(). But if doing a physical copy results in a logical copy, you can implement Copy to tell Rust to allow you to continue using the moved-from value. That's why I said

When you move something of a non-Copy type, the bits are still copied, but the original copy becomes unusable. The same bits are still there, but they no longer represent a valid value of that type. That's the only difference between a move and a copy, and also the only difference between Copy and non-Copy types.

4 Likes