Starting Rust : Borrowing and Onwership
Borrowing and ownership
Rust has known as different memory management model with other general languages, which replaces runtime garbage collection with compile-time checks for memory safety by borrowing and ownership. But before that lets look at what is Stack and scopes.
You can only access things in your stack frame. However we can only add things to the stack of a fixed known size by looking at the type of value, for example, i8 = 8bits. However, in case vector of characters or a String, how much memory will it take?. Now we need Heap not only Stack.
The rules of ownership
- The owner of a value is a variable
x =owns=> 10
- At any time, only a single owner is allowed
x, y=owns=>10 (not allowed)
x =owns=> 10
y =owns=> 10
When you assign variable to another for the types with known size, Rust will copy the value to the another.
However in case for the type whether size is not known. We know we get a pointer and the size of pointer.
x ====>pointer — →”hello world”
Can we then just copy this pointer to assign to another variable?
x ====>pointer — — — -”hello world”
y ====>pointer — — — — l
This is not allowed. the value “hello world” stored in the heap suddenly has two owners and breaks rule 2, ‘At any time, only a single owner is allowed’, because of if one changes the string there is no way for the other to know. The pointer get out of sync and when it is time to clean up the memory, two owners will try to clean up the value, “hello world”, which is disaster. Rust moves pointer instead of copying by making older variable invalid.
You can do x.clone() if you need variable with the String.
- The value is lost once the owner goes out of scope
You can return ownership back if you want.
But you don’t always passing around ownership and there is solution, Borrowing(Read only access)
The rules of borrowing
- Owners can have immutable or mutable references, but not both
- There can be multiple immutable references, but only one mutable reference
- References cannot be invalid