Professional Documents
Culture Documents
Chapter 3 - Ownership
Chapter 3 - Ownership
- set of rules that govern how Rust programs manage memory (heap)
* If any rule is violated → the program won’t compile
Stack vs Heap
1. Pushing to stack: faster than allocating on the heap
- stack allocator always puts data at top of stack
- heap allocator must find a big enough space to hold the data
2. Accessing data on stack: faster than accessing data on heap
- heap: must follow a pointer
- due to locality
Ownership rules
* Each value in Rust has an owner.
* There can only be one owner at a time.
* When the owner goes out of scope, the value will be dropped.
String:
- stored on heap
- mutable
- able to store an amount of text that is unknown at compile time.
----------------------------------------------------------------
* When s1 and s2 go out of scope, they will try to free the same memory.
= double-free error: memory safety bug leading to security vulnerabilities.
→ to ensure safety
* after let s2 = s1, Rust considers s1 as no longer valid. => called “move”
* Rust never automatically creates deep copies of data.
clone(): to copy heap data of the String along stack data (deep copy)
-------------------------------------------------------------------
let x = 5;
let y = x
* both x and y exist equal to 5.
data types with known size at compile time: stored on stack → copies are quick to make
* deep and shallow copies are the same thing
types with “Copy” trait: variables do not move, but are trivially copied.
→ valid after copy