Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Rust FAQ: Top Questions

2. How does Rust ensure memory safety without a garbage collector?

Rust achieves memory safety through its ownership system, enforced at compile time. The compiler checks rules around ownership, borrowing, and lifetimes to prevent memory leaks, dangling pointers, and data races.

  • Ownership: Each value has a single owner.
  • Move semantics: Transferring ownership invalidates the original reference.
  • Borrowing: References (immutable or mutable) allow temporary access without ownership.
  • Lifetimes: Ensures references are valid as long as the data they refer to.
fn main() {
    let s = String::from("Rust");
    takes_ownership(s); // ownership is moved
    // println!("{}", s); // error: value borrowed here after move
}

fn takes_ownership(text: String) {
    println!("{}", text);
}

Explanation: This prevents issues like use-after-free by enforcing access rules statically.