Files
rust-book-walkthrough/ownership
2026-10-06 20:58:16 +01:00
..
2026-10-06 20:58:16 +01:00
2026-10-02 15:52:53 +01:00
2026-10-02 22:51:32 +01:00

Ownership

The Stack and the Heap

The stack is fast memory which follows the Last in First out (LIFO) principle. On the stack, only data with a know size can live. If it can shrink or grow, then the data must be allocated to the heap. When data is allocated to the heap, it gets a pointer to an address in memory. Keeping track of these things are really important in languges like C. Other programming languages like Go use a garbage collector (GC) which cleans up data in memory on a regular basis. Rust does neither. It uses Ownership to manage memory and data, so each piece of data has an owner, and when that owner gets out of scope, the value is dropped.

Ownership rules

  • Each value in Rust has an owner.
  • There can only be one owner at a time.
  • When the owner goes out of scope, the value will be dropped.

Variable Scope

the scope of a variable is like this

{ // here `s` is out of scope, not declared yet
    let s = "text"; // here `s` is in scope

    // we can do stuff with `s` here ...
} // now `s` is out of scope

so when S comes into scope, it is valid. It remains valid until it is out of scope.

The String Type

So far we have talked about data types that are of known length, and are stored in the stack. Now we'll focus on data types that can grow, and are allocated to the heap. This example will use the String type. String is of an unknown length at compile time.

So consider this example

let mut s = String::from("Hello"); 

s.push_str(", world!"); // appends a literal to a string

println!("{s}"); // prints out "Hello, world!"

Memory and Allocation

A string literal, we know the value at compile time, so the value will be hard coded into the binary. Therefore, string literals are fast and efficient. With the String we must allocate an amount of memory on the heap, which by its very nature is unknown at compile time. that means that

  • memory must be requested by the memory allocator at runtime
  • We need a way to returning this memory to the allocator when we're done with our String When the String function is once again out of scope, i.e. the curly braces it is in are moved on, then Rust calls a special drop function to clean up the memory.