Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Rust FAQ: Top Questions

3. What is ownership in Rust?

Ownership is Rust’s unique system for managing memory. A variable owns a piece of memory. When ownership is transferred (moved), the previous owner can no longer use the data.

  • Move: Transfers ownership to a new variable.
  • Clone: Deep copies data.
  • Drop: Automatically called to deallocate memory when a variable goes out of scope.
fn main() {
    let a = String::from("Ownership");
    let b = a; // a is moved to b
    // println!("{}", a); // error: value moved
    println!("{}", b);
}

Explanation: This avoids double-free errors. Rust deallocates memory automatically but ensures it happens only once per value.