Jatin Raghav

Rust Memory Management.

Just 3 simple rules:

1-> Every value is accessed by a variable ( which is how all the high level languages work ), that variable is called its owner.

2-> At a given time a value can have only a single owner. ( that is, a single value can't be owned by multiple variables at the same time )

3-> When the owner goes out of scope the value is freed. ( the memory where the value was stored is freed )

That is the major chunk of it.

Inside the Rust compiler ( rustc ) we have a part inside it called the Borrow Checker, and that is the infamous thing.

Borrow Checker is the one that verifies whether everything checks out or not.

There are a few other side notes that go along with these 3 rules.

1-> By default Rust does not copy your values, it moves them.

References

References can be though of as pointers to the value they are referencing, they don't have the ownership of the value, so we are not breaking the 2nd rule with them. They are simply a way to get to the value using some other variable.

And since references are not owner of the value, the value is not freed when the reference goes out of scope.

Sometimes we just need to refer to some value and simply read it, and sometimes we want the ability to change the value. And If we don't want the ownership we can use references.

There are references for both reading ( called Immutable References ) and writing ( called Mutable References ).

Immutable References, these are used at places we don't want to update the value and just want to read it.

Mutable References, these are used at places when we also want to update ( mutate ) the value.

And regarding these references there are some rules we need to keep in mind.


Immutable references => These we can have in any amount, like any amount. But we can't have even a single one if there is a mutable reference in the same scope.

This is because Immutable reference reads value, and if we have a Mutable reference also in the same scope then the Mutable reference could change the value whenever it wants and we are cooked.

So, any amount of Immutable reference to throw around unless we have a Mutable reference in scope.

Mutable references => These can only be present one at a time. Since we don't want two variables to be able to update a value at the same time, that's kinda like breaking the second law. And if we do have one Mutable reference we can't have any Immutable Reference.

1 month ago | [YT] | 9