Ownership

Ownership is one of the three central pillars in Rust's memory model, where the others are Borrowing and Lifetimes. Ownership can be summarized in the following three rules:


 * Each value in Rust has a variable that’s called its owner.
 * There can only be one owner at a time.
 * When the owner goes out of scope, the value will be dropped.

When a value is transferred from one owner to another, this called a move. After the move, the previous owner can no longer access the value.

The trait
A scope is a region of code surrounded by curly braces. In the example above, the function  is a scope, and the parameters   and   as well as the local variables   and   only exist within this scope.

The ownership rules mention that values that go out of scope are dropped. Often, this means releasing a resource; for example, the type allocates memory and dropping it will free it. To do this, it implements the trait, which acts as a destructor. Whenever a value that implements  goes out of scope, this destructor is run automatically.

The trait
Some values, such as primitive types, are very small, so it's cheap to copy them. These types usually implement the trait. This means that they are are copied instead of being moved like all other values. Example:

This would not be possible if  didn't implement the   trait, because then   would be moved into   and accessing   after this would produce a compiler error. But thanks to the  trait, this works as desired.

As  types are constantly being duplicated and destroyed,   is mutually exclusive with. Copyable types should only ever be used to simply store some data (such as an integer or a character) rather than control an external resource (such as memory or a file).