“This is the 24th day of my participation in the First Challenge 2022. For details: First Challenge 2022.”


Not all memory is created equal. In most programming environments, programs can access stacks, heaps, registers, text segments, memory-mapped registers, memory-mapped files, and perhaps non-volatile RAM. But which one you choose to use in a particular situation has an impact on what you can store in that storage area, how long it stays there, and what mechanism you use to access it.

The details of these memory regions vary from platform to platform and are beyond the scope of this book, but some are so important to how you reason about Rust code that they are worth covering here.

Storage area terminology

Before delving into memory areas, you first need to understand the differences between values, variables, and Pointers.

A value in Rust is a combination of a type and an element of the range represented by that type. A value can be converted to a sequence of bytes using a representation of its type. But on its own, you could argue that a value is more like what you, the programmer, mean.

For example, the number 6 in type U8 is a mathematical integer 6, which is represented in memory as byte 0x06. Similarly, the string “Hello world” is a value in the range of all string representations and is represented in UTF-8 encoding. The meaning of a value is independent of where the bytes are stored.

A value is stored in a place, which is Rust’s term for “a place that can hold a value.” It could be on the stack, it could be on the heap, or it could be somewhere else. The most common place to store values is a variable, which is a slot on the stack named “the variable”.

A pointer is a number that holds the address of a memory region, so the pointer points to a place. Pointers can be “dereferenced” to access values stored in the memory location to which they point. We can store the same pointer in more than one variable, so that multiple variables indirectly point to the same location in memory and thus to the same underlying value.

The following code illustrates these three elements.

let x = 42;
let y = 43;
let var1 = &x;
let mut var2 = &x;
var2 = &y;
Copy the code