Ownership & Memory Model
Deep dive into Rust's ownership system, borrowing rules, and memory management, contrasting with JavaScript's garbage collection
Ownership & Memory Model
📖 Learning Objectives
Understand Rust's ownership system, its most fundamental concept. We will start from JavaScript's memory management and gradually understand how Rust ensures memory safety through compile-time checks.
🎯 Memory Management Comparison
JavaScript's Garbage Collection
JavaScript uses an automatic garbage collection mechanism:
Rust's Ownership System
Rust uses the ownership system to manage memory at compile time:
Memory Management Differences
- Automatic vs Manual: JavaScript automatic garbage collection, Rust compile-time checks
- Reference Semantics: JavaScript objects passed by reference, Rust by ownership transfer
- Memory Safety: JavaScript runtime checks, Rust compile-time guarantees
- Performance: JavaScript has garbage collection overhead, Rust zero-cost abstractions
🔄 Ownership Rules
Rust's Ownership Rules
Rust has three core ownership rules:
🔗 Borrowing & References
Immutable Borrows
Mutable Borrows
Borrowing Rules
📏 Lifetimes
Lifetime Annotations
🎯 Ownership & JavaScript Comparison
Data Passing Comparison
🎯 Exercises
Exercise 1: Ownership Transfer
Analyze the following code and identify where ownership transfer occurs:
fn main() {let s1 = String::from("hello");let s2 = s1;let s3 = s2.clone();println!("s2: {}", s2);println!("s3: {}", s3);}
View Answer
let s2 = s1;
- Ownership of s1 moves to s2let s3 = s2.clone();
- s2 is cloned, s3 gets ownership of new data- s2 is still valid because clone creates new data
Exercise 2: Borrowing Rules
Fix the borrowing error in the following code:
fn main() {let mut data = vec![1, 2, 3];let ref1 = &data;let ref2 = &mut data;println!("{:?}, {:?}", ref1, ref2);}
View Answer
fn main() {let mut data = vec![1, 2, 3];let ref1 = &data;let ref2 = &data; // Changed to immutable referenceprintln!("{:?}, {:?}", ref1, ref2);// Or use immutable reference first, then mutable referencelet mut data = vec![1, 2, 3];let ref1 = &data;println!("{:?}", ref1);let ref2 = &mut data; // Now a mutable reference can be createdref2.push(4);println!("{:?}", ref2);}
Exercise 3: Lifetimes
Add the correct lifetime annotations to the following function:
fn longest(x: &str, y: &str) -> &str {if x.len() > y.len() {x} else {y}}
View Answer
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {if x.len() > y.len() {x} else {y}}
📝 Summary
In this chapter, we deeply learned about Rust's ownership system:
- Ownership Rules: Each value has one owner, and the value is dropped when the owner goes out of scope.
- Borrowing System: Borrow data through references, avoiding ownership transfer.
- Borrowing Rules: At any given time, you can have either one mutable reference or multiple immutable references.
- Lifetimes: Ensure references are valid for their duration.
- Comparison with JavaScript: Rust compile-time checks vs JavaScript runtime garbage collection.
Key Takeaways
- The ownership system is at the core of Rust's memory safety.
- The borrowing system allows using data without transferring ownership.
- The lifetime system ensures references are always valid.
- These concepts are checked at compile time with zero runtime overhead.
Common Pitfalls
- Use after move: Value cannot be used after being moved.
- Simultaneous borrows: Cannot have mutable and immutable borrows simultaneously.
- Dangling references: Returning a reference to a local variable.
- Lifetime mismatch: Reference lifetimes do not match.
Next Steps
In the next chapter, we will learn about Rust's concurrency and asynchronous programming models, and how to safely handle multi-threading and asynchronous operations.
Continue Learning: Concurrency & Asynchronous Model
Module System and Build Tools
Learn Rust's module system, package management, and project structure, comparing them with JavaScript's modular development.
Concurrency & Asynchronous Model
Learn Rust's concurrency, asynchronous model, and multi-threading safety, contrasting with JavaScript's event loop mechanism