Chapter 04¶
The Stack and the Heap¶
Many programming languages don’t require you to think about the stack and the heap very often. But in a systems programming language like Rust, whether a value is on the stack or the heap affects how the language behaves and why you have to make certain decisions.
What Is Ownership?¶
Ownership is a set of rules that govern how a Rust program manages memory.
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.
Ownership in Function¶
Return Values and Scope¶
Returning values can also transfer ownership
Variable Scope¶
Memory and Allocation¶
- The memory must be requested from the memory allocator at runtime.
- We need a way of returning this memory to the allocator when we’re done.
Drop in Rust & RAII in C++¶
Note: In C++, this pattern of deallocating resources at the end of an item’s lifetime is sometimes called Resource Acquisition Is Initialization (RAII). The
dropfunction in Rust will be familiar to you if you’ve used RAII patterns.
Move¶
Shallow Copy
Clone¶
Deep Copy
References and Borrowing¶
Note: The opposite of referencing by using
&is dereferencing, which is accomplished with the dereference operator,*.
Dangling References¶
The Rules of References¶
Mutable References¶
Mutable references: have one big restriction, if you have a mutable reference to a value, you can have no other references to that value.