Module lessons (1/2)
Ownership: Stack, Heap, Move, Clone and Copy
Understanding RAII and drop automatically, because the assignment of String performs a Move in O(1), when Clone and Copy are needed.
What you'll learn in this lesson
- Apply the three fundamental rules of Rust Ownership (RAII without Garbage Collector).
- Distinguish between
Copytypes on the Stack (i32,bool,&str) and types on the Heap subject to Move (String,Vec<T>). - Make conscious choices when transferring ownership vs duplicating data with
.clone().
Overview
C and C++ leave the programmer free to call free() (risking use-after-free or double free). Java, Go and Python delegate everything to a garbage collector at runtime. Rust chooses a third way: it checks the ownership of each value at compilation.
A variable String saves only three machine words on the Stack (ptr, len, capacity), while the characters live on the Heap. When you write let s2 = s1;, Rust doesn't copy the bytes to the Heap: it copies the 3 fields to the Stack and invalidates s1 to prevent a double free at the end of the block!
Sections covered in this lesson
- 11. The three golden rules of Ownership
- 22. Stack (
Copy) vs Heap (Movein O(1)) - 33. Interactive Stack/Heap & Move Simulator
- 44. Switching to functions and explicit
Clone - 5Practical exercises
- 6Check for understanding
Unlock "Ownership: Stack, Heap, Move, Clone and Copy" and the full Course Rust curriculum
Understanding RAII and `drop` automatically, because the assignment of `String` performs a Move in O(1), when `Clone` and `Copy` are needed.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course Rust plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.