Bindings in Rust: Much More Than Just Variables

Parameter passing, stack, heap, and the state of an instance

The French version of this page is available here

This post is the second episode of a series of 4. If needed, start with episode 1. The list of episodes is at the end of the page.

TL;DR

  • Parameters are passed via the stack. Only data whose size is known at compile time goes there.
  • That’s why a Vec<T> comes in 2 pieces: a fixed-size control structure (PLC) on the stack and the data on the heap.
  • Physically, the stack and the heap are both mutable. The static analysis done by the compiler enforces the properties of the bindings, and it costs nothing at runtime.
  • Mutability is therefore a property of the binding, not of the data.
  • A binding links a name to the state of a concrete instance (think of the hash code), not just to a “value”.

Table of Contents

Where Are We?

In episode 1 we started from the Rustlings exercise move_semantics3.rs and we stopped on its first line of code:

let vec0 = vec![22, 44, 66];

We saw that vec0 is an immutable binding and that mutability is a property of the binding, not of the data. Then we started a first detour to understand what happens in memory. This is where we left off: a Vec<T> is made of a control structure (PLC for pointer, length, capacity) which is on the stack, and of a dataset which is on the heap.

Rust stack heap

Two questions were left open: why split a vector into 2 pieces? And if mutability is a property of the binding, is the data itself modifiable?

A second detour to understand parameter passing, the heap and the stack

But why is it so complicated? Sorry, but we’re going to have to take an extra detour to understand why a vector is separated into two parts. Indeed, we need to understand the basic principle of passing parameters from one function to another, and then introduce the two memory areas, heap and stack. Once that’s done, we’ll be able to truly understand why mutability is the mutability of the binding and not the data.

Here we go again. Imagine… Imagine that we are in a function main(). We want to call another function and pass it a parameter. Let’s keep it simple to start. Let’s imagine that we want to pass an integer value 1 . In order to properly decompose the events, we will use the PC that we saw in The 3-Body Problem.

L'ordinateur humain ALU
ALU 3 bodies problem

So? How do we do it? I suggest we put the value in a workbook, give this workbook to a rider, and send the rider to the other end of the plain. There, we open the workbook, retrieve the value, and execute the function code, taking into account the received value. When it’s finished, the rider returns. The workbook is empty because the function didn’t return anything. We then resume executing the function main().

Cool, that works. Now if we want to pass 2 integers. Same principle. However, be careful with the order. I have to agree with the function to say that the first sheet of the workbook corresponds to the first parameter and the second to the second parameter. For example, in the C++ specifications nothing forces the compiler to respect a particular order (MSVC goes from right to left, clang from left to right), in Forth and assembler the parameters are passed from right to left…

Cool, it still works. And now if I want to pass a real number (3.14159) and an integer (42). Same here, I pay attention to the order and write 3.14159 on one page and 42 on the other.

Cool, it continue to work. Now let’s imagine that I want to pass an array of pixels (an image) whose size is known at compile time (640x480 pixels all coded on one byte each). Here, it’s longer but I’m going to use 640x480 pages and put on each one a value between 0 and 255. At the end the function will read all the pages of the workbook and be able to reconstruct the image locally.

Well, that’s it, we’re done! Yeah… Almost… What happens now if I want to pass an array of numbers whose length I don’t know at compile time? Also think about cases where I want to pass an array whose length is likely to vary during program execution. This is called a vector.

vecteur

We’re dead… It’s not possible… Indeed, you’re right, when the rider arrives, the function won’t know how many pages it has to pop (read) from the binder. That said, we can get out of it if we apply the principle of indirection (“All problems in computer science can be solved by another level of indirection.” [David Wheeler]).

Basically, instead of passing the vector itself, we will pass the description of the latter. It has a fixed size. For example, we can decide to describe a vector with 2 pages in the workbook. One page contains an integer that indicates the number of values ​​in the vector and another page indicates with another integer, the place in the field, where to fetch the values ​​when we need them. Everything happens as if we were passing a vector of variable size to the function, but this comes at the cost of slower provision. Indeed, instead of reading the values ​​of the vector directly from the pages of the workbook, we will have to make a rider go back and forth to the other end of the field to retrieve the values ​​we will need.

We can remember that:

  1. the stack
    • allows you to store local variables
    • when a function calls another function passing it parameters
      • it puts the latter on the stack (push)
      • the function retrieves them in the correct order (pop)
    • we only put parameters of known size and simple types (trivially copyable) in the stack: int, bool, float, fixed array, tuple & struct with simple types, memory addresses
  2. the heap is a free area of ​​the field where you can drop things
    • these things (data structures) can have dynamic sizes
    • everyone (all functions) who knows where a thing is (it know its address) can access it in reading or writing

So we understand why the vector is composed of 2 pieces:

The control structure: It has a fixed size, known at compile time. It can be passed onto the stack to “pass” the vector to a function.

  • If the vector vec0 is mutable, the parameter len may change from 3 to 18 but this value will always be coded by one usize (think of a 64-bit integer).
  • Likewise, if for some reason we have to move the area containing the data (we go from 3 to 300 data for example and we run out of space), the address (the value of the pointer I mentioned previously) will change but it will always be a 64-bit address.
  • So, even if the values ​​of the fields in the control structure change, its size, the number of bytes it occupies, will always be the same.
  • It is this fixed-size structure that we will pass from one function to another via the stack.

The dataset:

  • It is likely to see its size evolve.
  • So we store it on the heap.

Ok, ok… I understand why a dynamic data type like a vector is split into 2 parts (descriptive on the stack and data on the heap) but where are the stack and the heap?

In the context of a process (an executable) running under Windows, this is (roughly) what the memory map looks like (it’s similar under Linux. Under Mac, I don’t know).

+-------------------------+ ← High addresses (ex: 0xFFFFFFFFFFFFFF)
|      Kernel Space       | ← System reserved (not accessible)
+-------------------------+
|     Stack (grows ↓)     | ← Local variables, function returns
|                         |   Dynamically allocated at runtime
+-------------------------+
|  Guard page / padding   | ← Stack overflow protection
+-------------------------+
|       Heap              | ← new / malloc : dynamically allocated
|   (grows upwards ↑)     |
+-------------------------+
|   BSS Segment (.bss)    | ← Global variables NOT initialized
+-------------------------+
|   Data Segment (.data)  | ← Global variables initialized
+-------------------------+
|   Code Segment (.text)  | ← Executable code, functions
+-------------------------+
|     PE Headers (.exe)   | ← PE file headers (Portable Executable)
+-------------------------+
|    NULL Page (invalid)  | ← Causes segfault in case of dereferencing
+-------------------------+ ← Address 0x0000000000000000

And if I simplify further, here is what we need to remember:

Rust stack heap
  • The executable program (the process) believes that it is “Cast Away”, alone in the world (say hi to Wilson)
  • This idiot thinks he has access to a 64-bit memory space with addresses from 0x00.. to 0xFF.. In fact, it’s the OS that makes him believe that, but no, of course, he’s in a virtualized memory space.
  • The code that is executed is located in the “Code Segment” section.
  • Then there are 2 areas which contain the initialized and uninitialized global variables respectively.
  • The size of the memory block [.text + .data + .bss] is fixed and known at the end of compilation and linking. So that’s good, it will not change.

When the program starts, the processor executes the instructions that are in the segment .text. If it needs the value of a particular global variable, it looks for it in the area .data.

Then, if the program needs to create a local variable it will do so in the stack and if it needs to allocate a memory area it will do so in the heap.

To give you an idea, on Windows, the main process’s stack size is 1MB (4KB are pre-allocated to save time). This is configurable if needed. Then each created thread has its own stack whose default size is 2MB (this is also configurable).

Regarding the heap, we will say that initially its size is 0.

And what happens if the downward-growing stack meets the upward-growing heap? That’s a cross of streams, and everyone knows you should never cross the streams. That would be bad.

What you need to remember at the end of this second detour:

  • Parameters passing is done via the stack
  • Data whose size is fixed and known at the end of compilation is placed there
  • The heap and the stack are two similar memory areas.
  • They are both read-write and grow towards each other.
  • Since Vec<T> it is variable length, it cannot pass through the stack
  • We therefore decided to break it down into 2 parts
    • A PLC structure, of fixed size and which can be passed through the stack
    • The values ​​that are on the heap

And there you have it. You understand why Vec<T> it’s so “complicated”. It’s just because we wanted to be able to pass it as an argument to a function.

End of the second detour. Back to the question concerning the mutability of data in memory.

As we have seen, the heap and the stack are in the virtual memory space that the program perceives. “Physically” these two areas are mutable. For example, we don’t have the means to store immutable data in read-only memory.

So to answer the question: yes, potentially the data (whether on the heap or in the stack) is all mutable.

What guarantees that the correct read and write operations are performed on the data (whether in the stack or the heap) at runtime is the static analysis of the code that is done during compilation. The compiler does not treat this or that memory location (stack or heap) differently. It monitors the bindings and their properties. From its point of view, there is no difference in treatment between the stack and the heap. What matters is that the bindings’ properties are met.

It’s like in C++. If I declare a variable const, whether it’s on the heap or in the stack, if I modify it I get hit on the fingers with a ruler (and the ruler is made of metal, not rotten plastic).

At our level, we can imagine that during compilation, there is a table which takes inventory of all the bindings, of all the memory zones and that if at some point, a piece of code tries to modify an immutable binding, the compiler screams.

The thing is, this heavy, long, and tedious analysis only takes place during compilation. The goal is that at the end of the latter, we know for sure that at the time of execution everything will go well and that we will not try to modify an immutable binding for example.

Finally, when everything is proven, when the code is compiled, we go for it. At runtime there are no more tables or anything else. Everything happens as if the day before the MotoGP tests you take your bike and go for a lap of the track. You go slowly, you note everything. The little bump here, the dip there, right at the apex, the spot to use as a braking point… You go slowly and if necessary you retrace your steps. When it’s clear, when everything is checked, the next day you don’t ask yourself any more questions… Full throttle!

moto gp

One last note before moving on. For now, we’ve only seen the “mutability” property of the binding, but nothing prevents us from adding others. For example, lifetime properties. We’ll come back to it in episode 4. And this, unless I’m mistaken, is not tracked by a C++ compiler.

What to remember at the end of the first detour:

  • From the compiler’s point of view, the stack and the heap are memory areas where one can read or write
  • The data is therefore potentially always mutable.

End of the first detour. Back to the question concerning the mutability of the binding

Okay… And about the mutability of the binding. Don’t try to pull the wool over my eyes. You still haven’t answered my question!

In fact, considering the code test we did and the 2 (long) detours we took, it is clear that:

  • Data, whether on the heap or in the stack, it doesn’t matter, is always modifiable.
  • The compiler knows the mutability properties of different bindings
  • During static analysis the compiler detects if the code tries to do something forbidden (modify an immutable binding for example)
  • What is allowed or forbidden is what is written as property in the binding

So yes, I confirm mutability is a property of binding

End of analysis of the 1st line of code

We’re still on the first line of code (at this rate we’re not out of the woods yet…)

let vec0 = vec![22, 44, 66];

On the other hand, big progress… From now on we understand the sentence: vec0 is an immutable binding which links the name vec0 to the complete state of a concrete instance of Vec<i32>.

Um… Sorry… I understand 80% of the sentence but I don’t understand why you’re talking about “the complete state of a concrete instance”. In fact, it took me a long time to get to this sentence. Let me explain, and for that, we start from the line of code:

let vec0 = vec![22, 44, 66];

What you’ll read here and there is usually stuff like “a binding links a name to a value”.

In the specific case of the line of code you might read things like: “vec0 is an immutable binding that binds the name vec0 to the value Vec<i32>”

OK… Great, but what is the value? The PLC part of the vector? The values ​​in the table? Actually, it’s all of these things at once. Since I had a lot of trouble with the word “value” in the case of a vector, my first idea was to tell myself that the “value” of a vector (or any other non-trivial data structure) is the hash code of the instance.

Typically I can construct and display the hash code of an instance Vec<T> with the code below:

use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

fn main() {
    let vec0 = vec![22, 44, 66];

    // Create a new hasher
    let mut hasher = DefaultHasher::new();

    // Feed the vector into the hasher
    vec0.hash(&mut hasher);

    // Finalize the hash and get the result as a u64
    let hash_code = hasher.finish();

    // Print the hash code
    println!("{}", hash_code); //2786706741450235691
}

It was becoming clearer to me and I could say to myself: vec0 is an immutable binding that links the name vec0 to the hash code of the vector instance. And there “Bingo, here is DNA dyno…”. No, not quite but “Bingo, now I understand that if I modify one of the PLC values ​​or one of the table values ​​I will take one because that will modify the hash code value.”

But if you think about it, the hash code captures and synthesizes, in a single value, the state at a given time t of the instance I have in my hands. In other words, if I now talk about state rather than hash code, it amounts to the same thing.

The description of the first line of code evolves and becomes:

  1. vec0 is an immutable binding that binds the name vec0 to the state of a Vec.
  2. vec0 is an immutable binding that binds the name vec0 to the full state of a Vec. This is to say that in a vector it concerns the data and the control structure.
  3. vec0 is an immutable binding that binds the name vec0 to the full state of an instance of Vec<i32>. Yes because in the code I manipulate instances rather than types.
  4. vec0 is an immutable binding that binds the name vec0 to the full state of a concrete instance of a type Vec<i32>. Probably too much. It’s just to emphasize that the instance in question is something like Vec or String and not really an abstract type (Trait).

Finally, what I keep in mind is: blah blah blah is a (im)mutable binding that binds the name blah blah blah to the state of a concrete instance of a type <T>.

That being explained, let’s go back and about the first line of code

let vec0 = vec![22, 44, 66];

We can say that vec0 is an immutable binding that binds the name vec0 to the complete state of a concrete instance of a type Vec<i32>.

  • vec0 this is the name of the binding (introduced by let)
  • The vector consists of a PLC structure that is on the stack
  • Its pointer (P) points to the data [22, 44, 66] that is on the heap
  • The binding vec0 is not mutable.
  • If I touch anything that modifies the state (think of the hash code if necessary) of the vector (PLC or values) I get a slap in the face.

At this point, regarding the binding, you must keep in mind

  1. It associates a name with the state of an instance of a type
  2. It adds properties
    • of mutability
    • …
  3. Static code analysis ensures that the properties of the bindings are respected.

In episode 3 we finally move on to the second line of code and talk about ownership and move.

The Posts Of The Series

  • Episode 1: bindings rather than variables, binding mutability
  • Episode 2: parameter passing, stack, heap, and the state of an instance
  • Episode 3: ownership, move, and copy
  • Episode 4: references, borrowing, and lifetimes

  1. I know, integers don’t usually pass through the stack, but it’s just an example. ↩


Back to top

Published on: Dec 2 2026 at 11:00 AM | Last updated: Dec 2 2026 at 10:55 PM

Copyright © 1964-2026 - 40tude