Garbage collecting time and ownership

If you're used to any of the .NET languages, you'll be more than accustomed to the garbage collector (GC). Essentially, when all references to an object have gone out of scope, the object's heap allocation is freed up by the garbage collector. The garbage collector comes around every once in a while, basically checks through the whole space of allocated memory to see if something isn't used anymore, and removes such content from memory; in other words, the garbage left behind by a deallocated pointer is collected and removed.

Rust has a primitive garbage collector in the form of a reference counted container, Rc<T>. For most cases, it's not required though, as Rust uses a system known as ownership for allocation.

Up to this point, when we created a variable, we created variables that mostly live on the stack. These have a very short life span. When we create an object that lives on the heap, we create a single variable that points to it, but then we can have any number of objects point to it, or even through a copy of the pointer, have the copy become the base and free up the original. It gets messy and deallocation of the heap memory can lead to a variety of memory issues.

We can wrap any type in a generic container, Box<T>. This creates an owned pointer in Rust, which can only have a single owner, and when that pointer goes out of scope, the memory is automatically freed. In this way, Rust prevents a large number of the problems that we see in other languages. The point of this owned box is that we can hand out the box to other functions, thus being able to return heap allocated variables.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset