EMZETT.
Login

Rust: Ownership and borrowing – safe memory without a garbage collector

In short: Rust manages memory through ownership rules checked by the compiler: every value has exactly one owner, borrowing is controlled, and so neither memory leaks nor access errors arise.

In more detail: In C and C++ memory can be freed twice or read after being freed (use-after-free). Other languages use a garbage collector (Java, Go, Python). Rust solves this at compile time with ownership, borrowing and lifetimes: errors are found before the start, without runtime cost.

In Depth

The three rules

  1. Every value has one owner (a variable).
  2. There can be only one owner at a time.
  3. When the owner goes out of scope, the value is dropped.
let a = String::from("Hello");
let b = a;              // ownership moves to b (“move”)
// println!("{}", a);   // error: a is no longer valid
println!("{}", b);

Copies are explicit (b = a.clone()); simple values such as numbers are copied (Copy).

Borrowing: lending with references

Instead of handing over ownership you lend:

fn length(s: &String) -> usize { s.len() }   // immutable reference
fn append(s: &mut String) { s.push('!'); }   // mutable reference

Rule: either any number of reading (&T) or exactly one writing reference (&mut T) at the same time. This prevents data races and unexpected changes. The compiler’s borrow checker verifies this.

Lifetimes

A reference must not live longer than the value it points to. Usually the compiler recognises this; sometimes it needs hints ('a):

fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a.len() > b.len() { a } else { b }
}

This way there are no dangling pointers.

Assessment and learning

Advantages: memory safety without GC, high performance, safe concurrency. Disadvantages: steep learning curve, the compiler “fights” you at first, sometimes awkward for prototypes. Tips: read error messages carefully (they are very helpful), start with cloning and Rc/Arc, write small programs, use the book “The Rust Programming Language” and Rustlings exercises. With Rust, safe system programs, web services (Axum), WebAssembly and tools (ripgrep) are built.

See also: Stack and heap, Garbage collection methods, Memory leak, Rust