Ownership & BorrowingBeginner
1Question 1 of 1
rustHow do Ownership and Borrowing guarantee memory safety in Rust without a garbage collector?
Explanation & Concept
Rust manages memory through a strict compile-time **Ownership** system with three fundamental rules: 1. Each value in Rust has an owner variable. 2. There can only be one owner at a time. 3. When the owner goes out of scope, the value is automatically dropped (`Drop` trait).
**Borrowing Rules**: • You may have any number of immutable references (`&T`). • OR you may have exactly one mutable reference (`&mut T`). • But never both simultaneously, preventing data races at compile time.
Code Example
rust
fn main() {
let mut greeting = String::from("Hello");
// Immutable borrow
let r1 = &greeting;
let r2 = &greeting;
println!("{} and {}", r1, r2); // Valid!
// Mutable borrow (only after immutable borrows are no longer used)
let r3 = &mut greeting;
r3.push_str(", World!");
println!("{}", r3);
}How It Works & Key Takeaways
The Rust borrow checker verifies at compile-time that references cannot outlive the data they point to, eliminating null pointer dereferences and memory leaks.
Mock Test · 1 Questions · Optional
Ready for Traits & Generics?
Take a quick test to evaluate yourself, or move straight to the next module.
Beginner1 questions