Moving ownership in Rust
The move operation in Rust is similar to a shallow copy in other programming languages. This concept can be seen in action when assigning a variable to another variable, or when passing a variable to a function as a parameter. But first, to understand things better, let’s briefly introduce the concept of ownership.
Ownership
Every value in Rust has a variable that is known as its owner. There can only be one owner at a time that is dropped when it goes out of scope. Dropping is equivalent to cleaning the memory allocated on the heap when it can no longer be accessed.
Moving ownership
fn main() {let x = String::from("Hello World!"); // x is the first ownerlet y = x; // y becomes the new ownerprintln!("y = {}", y); // Using 'x' will give an error}
In the code above, the x variable is the first owner of Hello World!. Since the String data type in Rust does not implement the Copy trait, its ownership gets transferred to y in line 3. If x loses its status as the owner, using it will generate a compile-time error.
However, if a Copy type (e.g., an integer) is used, a move won’t occur. Instead, the value of x will be copied into y; so, x still remains usable after it is assigned to y:
fn main() {let x = 10; // x is the ownerlet y = x; // y is the owner of another value// Both 'x' and 'y' are usable:println!("x = {}", x);println!("y = {}", y);}
Free Resources