Rust Ownership and Memory Management

by mahidhar

Ownership and Memory Management:

Ownership:

Rust's ownership system is central to its memory safety guarantees. Each value in Rust has a variable that owns it, and there can only be one owner at a time. When the owner goes out of scope, the value is dropped. This ownership model prevents common issues like null pointer dereferencing and memory leaks.

Simple Example:

code
fn main() {
    let s = String::from("hello"); // s owns the string

    let len = calculate_length(&s); // passing a reference to s

    println!("The length of '{}' is {}.", s, len);
}

fn calculate_length(s: &String) -> usize {
    s.len()
} // s goes out of scope, but because it's a reference, nothing happens

Complex Example:

code
fn main() {
    let mut s = String::from("hello"); // s owns the string

    change(&mut s); // passing a mutable reference to s

    println!("{}", s);
}

fn change(s: &mut String) {
    s.push_str(", world"); // modifying the string
}
Borrowing:

In Rust, borrowing allows you to pass references to values without transferring ownership. References can be immutable or mutable, and the borrow checker enforces strict rules to prevent data races and dangling references.

Simple Example:

code
fn main() {
    let s = String::from("hello");

    let len = calculate_length(&s); // borrowing a reference to s

    println!("The length of '{}' is {}.", s, len);
}

fn calculate_length(s: &String) -> usize {
    s.len()
}

Complex Example:

code
fn main() {
    let mut s = String::from("hello");

    change(&mut s); // mutable borrow

    println!("{}", s);
}

fn change(s: &mut String) {
    s.push_str(", world"); // modifying the string
}
Ownership Rules:

Rust's ownership rules ensure memory safety without the need for garbage collection. The rules include:

  • Each value in Rust has a single owner.
  • Ownership can be transferred using moves or borrowed using references.
  • References must follow strict lifetime rules enforced by the borrow checker.

Ownership Rules Table:

Situation

Result

Single Ownership

Ok

Transfer Ownership

Ok

Multiple References

Compiler Error (Borrow Checker)

Mutable Borrow

Single Mutable Reference

Immutable Borrow

Multiple Immutable References

This covers the fundamentals of ownership and memory management in Rust. In the next section, we'll explore data structures in Rust.