ownership
Three rules:
- each value has an owner
- there is only one owner at a time
- when the owner goes out of scope, the value is dropped
That is the whole system Everything else is a consequence
Stack and heap
Fixed size values live on the stack
Values whose size is unknown at compile time, such as String, allocate on the heap
The restaurant analogy is apt: the stack is a pile of plates, the heap is a restaurant table you are shown to
Pushing onto the stack is faster Accessing heap data needs a pointer indirection That is why Rust cares so much about heap ownership
Move
let s1 = String::from("hello");
let s2 = s1;
String has three parts on the stack: pointer, length, capacity
The assignment copies those three, not the heap data
Rust then invalidates s1
When s2 goes out of scope it frees the memory
No double free, no copy of the string
In C++ that would be a shallow copy and a bug In Rust it is a move, and the compiler enforces it
Clone
let s1 = String::from("hello");
let s2 = s1.clone();
clone is the expensive one
It copies the heap data
When you see clone, you know arbitrary code ran and memory was allocated
That is a useful visual signal
Copy types
Integers and other fixed size types implement Copy
They are trivially copied, not moved
let y = x leaves both valid
This is the difference between deep and shallow copying, and why Copy is not allowed on types that need Drop
Scope and drop
When a variable goes out of scope, Rust calls drop
For a String, that returns the heap memory
For a Vec, the elements and the buffer
You do not call it yourself
Functions
Passing a value moves or copies, just like assignment
Returning a value transfers ownership out
The example of takes_ownership and makes_copy is the clearest picture of this
Returning ownership
fn takes_and_gives_back(a_string: String) -> String {
a_string
}
That ceremony is tedious Rust solves it with references, which is the next chapter
Next
Borrowing in 04 borrowing
Posted