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
, andpointers
), automatically implementCopy
. - Manual Implementation: For user-defined types, we can implement
Copy
(often together withClone
) 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.
- Automatically Implemented: Some types, like primitive types (e.g.,
-
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 theClone
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.