In Rust, the ownership (Ownership) system is one of its core features, enabling Rust to ensure memory safety without a garbage collector. The three main rules of ownership are as follows:
-
Ownership Rules for Variables:
- Every value in Rust has a single owner, which is a variable.
- At any given time, a value has exactly one owner.
- When the owner (variable) goes out of scope, the value is dropped.
For example, when a variable is created within a function, it becomes the owner of a value. Once the function containing the variable completes execution, its scope ends, and Rust automatically invokes the
dropfunction to free the memory used by the variable. -
Move Semantics (Transfer Rules):
- When ownership is transferred (e.g., by assigning to another variable), the resource is moved to the new owner.
- The original variable becomes invalid after ownership transfer and cannot be accessed or used.
For instance, if you have two variables
aandb, andahas already allocated some memory resources, after executinglet b = a;, ownership ofais transferred tob. Subsequently, attempting to accessaresults in a compilation error. -
Borrowing Rules:
- Rust allows borrowing values through references, but during borrowing, the original data cannot be modified or reassigned to another owner.
- References come in two types: immutable references (
&T) and mutable references (&mut T). - At any given time, you can have at most one mutable reference or multiple immutable references, but not both simultaneously.
- References must always be valid.
For example, if you have a mutable reference
&mut data, you can modify the data it points to. However, during this period, you cannot create any other references todata. This ensures that the data remains unchanged while the reference is valid, preventing data races.
These rules work together to enable Rust to catch many memory errors and concurrency issues at compile time rather than runtime, enhancing program safety and efficiency.