Skip to main content
Module 3 · Lesson 1 of 25/24 in the course~25 min
Module lessons (1/2)

Ownership: Stack, Heap, Move, Clone and Copy

Lesson preview5 hands-on exercises readyCourse Rust · Module 3 — Ownership, Move and Borrowing

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 Copy types 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

  1. 11. The three golden rules of Ownership
  2. 22. Stack (Copy) vs Heap (Move in O(1))
  3. 33. Interactive Stack/Heap & Move Simulator
  4. 44. Switching to functions and explicit Clone
  5. 5Practical exercises
  6. 6Check for understanding
Pro Lesson · Module 3 — Ownership, Move and Borrowing

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.