Rust Ownership and Borrowing Explained With Examples

The borrow checker scares beginners, but ownership is a simple idea: every value has one owner, and borrowing lets others use it safely. Here is how it works, with examples.

Rust code in an editor

Rust ownership enforces memory safety at compile time: every value has exactly one owner, and when the owner goes out of scope the value is freed. There is no garbage collector, so the rules must be checked by the compiler.

Once you internalize three rules, the borrow checker stops being an enemy and becomes a safety net.

The three rules of ownership

Everything in Rust follows from these rules.

  • Each value has one owner at a time.
  • When the owner goes out of scope, the value is dropped.
  • You can either borrow a value or move it — borrows never take ownership.
If the compiler rejects your code, it is usually protecting you from a use-after-free or a data race that would have exploded in production.

Borrowing: shared and mutable

Borrowing lets you pass a value to a function without transferring ownership. You can have many shared (&) borrows or one mutable (&mut) borrow — never both at once.

That single rule — one mutable borrower or many shared borrowers — is what makes data races impossible in Rust.

A practical example

The most common beginner fix is passing references instead of moving values: use &String instead of String when you only need to read. It costs nothing and keeps ownership where it belongs.

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

    let length = calculate_length(&s);   // borrow, s stays valid
    append_exclamation(&mut s);          // mutable borrow

    println!("{length}: {s}");
}

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

fn append_exclamation(s: &mut String) {
    s.push('!');
}

Rust ownership FAQ

How long does it take to get comfortable with the borrow checker?

Most learners see a big breakthrough after a few weeks of daily practice. The borrow checker becomes second nature once you internalize the three rules.

Can I avoid ownership rules with garbage collection?

No — that would defeat the purpose. If you want a garbage collector, use another language. In Rust you work with the rules, and they pay for themselves in reliability.