Rust with diagrams: Ownership 1 - Rust's memory approach

Rust with diagrams: Ownership 1 - Rust's memory approach

Rust documentation with diagrams to fast learn and remember. Let's learn together in Chapter 4.1.

Before understanding Ownership, we should know about Rust's memory approach.

Memory: STACK & HEAP

Rust has two different ways to handle data in memory:

Stack: better performance, first in first out, size and type is known in compile time, fixed size.

Heap: size and type can be unknown in compile time, size unfixed and can be modified.

How does Rust assign data into STACK and HEAP?

Data sent to the Stack is faster and more direct than data sent to the heap because the Heap needs to finds empty spot big enough before assigning it.

When data is assigned in to the Heap, a Pointer is created, functioning like a reference that allows for fast data retrieval. Pointer address can be assigned to the Stack optionally.

How does Rust drop data? with Garbage Collector?

  • Rust hasn't Garbage Collector.

  • It's our responsibility to identify when memory is no longer being used and to call code to explicity free it.

  • The memory is automatically returned once the variable that owns it goes out of scope.

    • When it happens: Rust calls a special function for us. Called "drop" at the closing curly bracket.

    • Rust implements RAII Patterns.

Assigning data into Stack & into Heap

const x = 5; // data into the Stack
const n: i32 = 5; // data into Stack specifying size

let s1 = String::from("hello"); // data into Heap

Into Stack is very clear, but into Heap we need to specify the type (String in this case). :: operator allows us to namespace this particular from function under the String type rather than using some sort of name like string_from .

Next article

Once we understand the Rust's memory approach, we can delve deeper into Ownership. In the next article I will summarize how how data interacts in memory, both in the Stack and the Heap.

Read next article


I wish that this content helps you to learn Rust while i do it. If you have doubts, suggestions or you see errors, please don't be shy and comment on them. The goal of this content is learn together!

References: