Rust: Ownership and Borrowing
Ownership in Rust

Ownership = binding/association of value to a variable. The rules are:

Only one owner at a time.

If the binding is “released”, ownership is “gone” and data is “freed”.

let p1 = Person::new(); //1

p2 = p1; //2 let p1 = Person::new();

do_something(p1); //out of scope

On line 2, p1 will be freed. It's out of scope since it has transferred ownership to p2 . Passing p1 into another function also has the same effect.

let p1 = Person::new();

p2 = p1;

println!("person {#:?}", p2)

println!("person {#:?}", p1) //compile error

That’s the reason Rust does not allow you to use that value again. It enforces this at compile time using borrow checker.

Drop

It is possible to implement the drop method from the Drop trait if custom cleanup logic is required. It will be automatically called by Rust when that value goes out of scope

Once a variable is out-of-scope, i.e. its ownership has been relinquished, the Rust compiler will not allow you to use it again, since it needs to be “freed”. This is also called Moving , i.e. ownership of p1 moved to p2 .

Ownership is applicable to heap data only, not stack data since it (stack data) is “copied”, not “moved”.

Copy

The Copy trait allows a value to be copied. All the primitive types (e.g. i32 , bool , etc.) implement Copy implicitly.
['Abhishek Gupta']
['Coding', 'Programming', 'Beginner', 'Rust', 'Rustlang']