Rust: What problem does ownership solve that garbage collection cannot?
Photo: Wikimedia Commons

Rust: What problem does ownership solve that garbage collection cannot?

It's not about speed. The key is to catch an entire class of errors at once during compilation.

Rust is often described as "as fast as C but safe." That description is accurate, but it leaves out the most interesting part: the mechanism that makes it safe is also the mechanism that prevents most programming errors at the same time.

Three Fundamental Rules

  • Each value has exactly one owner
  • When the owner goes out of scope, the value is released—the compiler automatically inserts that instruction
  • At any given time, there are either multiple read-only references or exactly one writable reference; never both

The third rule is the most important one

A data race occurs when two threads access the same memory region at the same time and at least one of them writes to it. The "many reads or one write" rule is the negation of that situation.

That’s why the Rust compiler rejects programs with data races, even if you didn’t think about multithreading at all while writing them. This is something the garbage collector can’t do: it manages when to free memory, but it doesn’t manage who can access it and when.

The Price to Pay

Data structures with multiple mutual references—two-dimensional lists, graphs, and trees with back pointers—become difficult to express. You must use reference counting, indices instead of pointers, or accept controlled, unsafe code.

The learning curve is really steep. But most of the time when it feels like "the compiler is being picky," it turns out the compiler is just pointing out an error that, in another language, you’d encounter at runtime—at the most inconvenient moment.

Chia sẻ

Thảo luận