Copy or Move?

Who Decides if Something Is Copied or Moved? What Criteria Are Used?

  • Language Semantics: In Rust, the decision whether a type is copied or moved is made by the language’s ownership and type system. This decision is based on whether the type implements the Copy trait.

  • Implementing Copy:

    • Automatically Implemented: Some types, like primitive types (e.g., integers, floats, and pointers), automatically implement Copy.
    • Manual Implementation: For user-defined types, we can implement Copy (often together with Clone) if the type has a “trivial” bitwise copy semantics. This is usually acceptable when our type doesn’t manage resources (like heap memory, file handles, etc.) that require special cleanup.
  • Move Semantics: If a type does not implement Copy, then assignments and passing the type to functions result in moves. A move transfers ownership from one variable to another and invalidates the original binding (unless the type implements the Clone trait and we explicitly clone it).

Thus, the criteria are:

  • Does the type contain data that can be safely duplicated by a bitwise copy?
  • Does duplicating the type risk duplicating ownership of a resource?

If the answer is “yes, it can be safely duplicated,” then the type should implement Copy, and the language will treat operations like dereferencing a raw pointer as creating a copy.

Share Note
rocket

© 2023 KungFuDev made with love / cd 💜

Heavily inspired/copied from shuttle.rs