🦀 Rust Systems Programming & Memory Safety Masterclass
1️⃣ The Rust Revolution: Safety Without Garbage Collection
Definition: Rust ek modern systems programming language hai jo C/C++ jaisi direct hardware performance aur zero runtime overhead provide karti hai, bina kisi automated Garbage Collector (GC) ke, aur compile-time par hi 100% memory safety guarantee karti hai.
| Criteria | C / C++ | Java / Go | Rust |
|---|---|---|---|
| Memory Management | Manual (malloc / free). Prone to buffer overflows & dangling pointers. |
Automatic Garbage Collector (Stop-the-world pauses & runtime overhead). | Ownership System: Automatically freed at compile time when variable drops. |
| Runtime Cost | Zero overhead. Raw bare-metal speed. | High memory footprint due to GC metadata & object headers. | Zero-cost abstractions: High-level syntax compiles to optimized machine code. |
| Data Race Prevention | No compiler checks; runtime segmentation faults. | Runtime sync locks required; races still possible. | Compile-time error: Data races fail compilation via Send/Sync. |
2️⃣ Ownership Semantics: Move, Copy & Drop
1. Har value ka ek single variable Owner hota hai.
2. Ek samay par sirf ek hi owner ho sakta hai.
3. Jab owner ka scope khatam hota hai (closing brace
}), Rust value ko memory se automatically drop kar deta hai.
fn main() {
let s1 = String::from("FresherJobsAlert");
let s2 = s1; // MOVE occurs! Heap pointer transferred to s2.
// println!("{}", s1); // ❌ COMPILE ERROR: Value used here after move!
println!("{}", s2); // ✅ Valid: s2 is now the sole owner.
} // s2 goes out of scope → heap memory freed instantly!
3️⃣ References & Borrowing: Aliasing XOR Mutability
Bina ownership transfer kiye data access karne ke liye Borrowing use hoti hai:
| Borrow Type | Syntax | Cardinality Rule |
|---|---|---|
| Immutable Borrow | &T |
Aap kitne bhi shared immutable references ek sath bana sakte hain ($N$ readers). |
| Mutable Borrow | &mut T |
Ek specific scope me sirf ek single mutable reference allow hota hai (1 writer). |
4️⃣ Lifetimes ('a): Compile-Time Dangling Pointer Prevention
Lifetimes ensure karte hain ki references unke actual data source se zyada lambe samay tak zinda (alive) na rahein:
// Function returning reference with explicit generic lifetime 'a
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
// Compiler guarantees: Returned reference is valid as long as BOTH inputs remain in memory.
5️⃣ Enums, Pattern Matching & Robust Errors
Rust me null pointer exist nahi karta. Nullable states aur errors algebraic data types se handle hote hain:
// 1. Handling Nullability with Option<T>
enum Option<T> {
Some(T),
None,
}
// 2. Handling System Errors with Result<T, E>
enum Result<T, E> {
Ok(T),
Err(E),
}
// Exhaustive Pattern Matching:
fn inspect_package(salary: Option<u32>) {
match salary {
Some(amt) => println!("Offered Package: ₹{} LPA", amt),
None => println!("Offer pending negotiation."),
}
}
6️⃣ Smart Pointers: Heap Allocation & Shared Memory
| Smart Pointer | Target Location | Key Capability |
|---|---|---|
Box<T> |
Heap | Exact size stack par rakhna jabki heavy data direct heap par allocate hota hai (Recursive types). |
Rc<T> |
Heap | Reference Counting: Single-threaded multiple ownership (Free hota hai jab count 0 ho jaye). |
Arc<T> |
Heap | Atomic Reference Counting: Thread-safe multiple ownership across threads. |
RefCell<T> |
Stack / Heap | Interior Mutability: Borrowing rules compile-time ke bajay runtime par dynamically enforce karna. |
7️⃣ Fearless Concurrency: Send, Sync & Threads
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..5 {
let counter_clone = Arc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter_clone.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for h in handles {
h.join().unwrap();
}
println!("Final Thread-Safe Counter: {}", *counter.lock().unwrap());
}
•
Send: Type ka ownership ek thread se doosre thread ko transfer kiya ja sakta hai.•
Sync: Type ke references multiple threads dwara safely share kiye ja sakte hain (&T is Send).