Ownership: Managing Memory in Rust

James Bowen
The Startup
Published in
7 min readDec 2, 2019

--

When we first discussed Rust we mentioned how it has a different memory model than Haskell. The suggestion was that Rust allows more control over memory usage, like C++. In C++, we explicitly allocate memory on the heap with new and de-allocate it with delete. In Rust, we do allocate memory and de-allocate memory at specific points in our program. Thus it doesn't have garbage collection, as Haskell does. But it doesn't work quite the same way as C++.

In this article, we’ll discuss the notion of ownership. This is the main concept governing Rust’s memory model. Heap memory always has one owner, and once that owner goes out of scope, the memory gets de-allocated. We’ll see how this works; if anything, it’s a bit easier than C++!

For a more detailed look at getting started with Rust, take a look at our Rust video tutorial!

Scope (with Primitives)

Before we get into ownership, there are a couple ideas we want to understand. First, let’s go over the idea of scope. If you code in Java, C, or C++, this should be familiar. We declare variables within a certain scope, like a for-loop or a function definition. When that block of code ends, the variable is out of scope. We can no longer access it.

int main() {
for (int i = 0; i < 10; ++i) {
int j = 0;

--

--