Part 2: Ownership, Borrowing, and Lifetimes - Rust's Memory Safety
Introduction
Why Ownership Exists
The Memory Management Spectrum
char* data = malloc(1024); // Allocate
// Use data...
free(data); // Must remember to free!
// Later use of data = segfault or security vulnerabilityThe Three Ownership Rules
Rule 1: Single Owner
Rule 2: Automatic Cleanup
Rule 3: Move Semantics
Real Example: Payload Management
Borrowing - Using Without Owning
Immutable References (&T)
Mutable References (&mut T)
Borrowing Rules
Real Example: HTTP Client Sharing
Clone vs Copy
Copy Types (Stack-only)
Clone Types (Explicit Copy)
In My Project
Lifetimes - Ensuring References Are Valid
The Problem Lifetimes Solve
Lifetime Annotations
Lifetime Elision (Compiler Infers Lifetimes)
Lifetimes in Structs
Real Example from My Scanner
Smart Pointers
Box - Heap Allocation
Rc - Reference Counted (Single-threaded)
Arc - Atomic Reference Counted (Thread-safe)
Real-World Pattern: Scanner Implementation
Common Ownership Patterns
Pattern 1: Taking Ownership for Consumption
Pattern 2: Borrowing for Inspection
Pattern 3: Borrowing Mutably for Modification
Pattern 4: Returning Owned Data
Fighting the Borrow Checker
Common Error: Multiple Mutable Borrows
Common Error: Borrowing Moved Value
Iterator Ownership
Key Takeaways
When to Use What
Next in Series
PreviousPart 1: Getting Started with Rust - Setting Up and Basic TypesNextPart 3: Error Handling and Result Types - Robust Production Code
Last updated