Copy or Move?

20 February 2025
Copy or Move?
Rust 101 (4 Part Series)
Welcome to Rust 101! This series covers my exploration of Rust, from basic concepts to more advanced topics. It's not in any particular order — just a collection of things I find interesting or at least interesting enough to write a post or note about. If you're curious about Rust, feel free to jump into any post that catches your eye.

Note:This is a personal note — originally written for myself from old drafts scattered across Obsidian, Notion, and Anytype. It may be simple, incomplete, or not perfectly organized, but I've refined it with help from AI. I hope it sparks curiosity and conversation!

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 article
rocket

© 2023 KungFuDev made with love / cd 💜

Heavily inspired/copied from shuttle.rs