3 ms·
No problem. :) That's not quite it. It's more about compile time vs runtime. Arc and GC are runtime tracking of "when can this be freed." Ownership is compile-
by steveklabnik 6y ago
No problem. :)
That's not quite it. It's more about compile time vs runtime. Arc and GC are runtime tracking of "when can this be freed." Ownership is compile-time tracking of the same. Rust has refcounted types in its standard library, but you only need to use them relatively rarely. Here's a small example with not too much syntax. The core idea:
fn main() {
// String is a heap allocated, mutate-able string type
let s = String::from("foo");
} // s goes out of scope here, and so will be freed here;
// the compiler generates the code to free the heap allocation at this point
s is the "owner," and there's only one, so this can be tracked fully at compile time.
Onwership can move, too. Let's introduce a function:
fn foo(bar: String) {
// body would go here, elided to keep this simple
} // because bar is of type "String", this function "takes ownership" of the
// value passed as 's', and so the compiler will generate the code to free
// its heap allocation at this point
fn main() {
let s = String::from("foo");
// we pass s to foo...
foo(s);
} // ... and because we did, it no longer exists in main, and the compiler
// knows this, so no code to free the allocation is generated here. if
// it were, this would lead to use-after-free.
All of this is trackable, 100%, at compile time. So there's no runtime overhead here at all.
But imagine that foo() creates a new thread inside of it, and we want to access said string from inside that thread, as well as from within main. Now we have multiple owners, not a single one, and it's not possible at compile time to know when the string should be freed. The simplest solution here is to reach for reference counting, and you'd end up with Arc<String>, that is, a String that's wrapped in an atomic reference count.
(Also, references don't take ownership, so if you didn't want to have foo free its argument, you'd have it accept a reference, rather than a String directly. This would let you temporarily access the string, without freeing the backing storage when the function's body has run its course.
- mikewarot 6y agoWow... that's quite a bit more than Garbage collection... thanks for explaining it.