A bit confused what a variable is
⚓ Rust 📅 2025-05-07 👤 surdeus 👁️ 11Just following this example from the interactive book:
fn main() {
let mut x: Box<i32> = Box::new(1);
let a: i32 = *x; // *x reads the heap value, so a = 1
*x += 1; // *x on the left-side modifies the heap value,
// so x points to the value 2
let r1: &Box<i32> = &x; // r1 points to x on the stack
let b: i32 = **r1; // two dereferences get us to the heap value
let r2: &i32 = &*x; // r2 points to the heap value directly
let c: i32 = *r2; // so only one dereference is needed to read it
}
* is "clicking" on a reference, following a heap pointer to the value. And also allows updating in this case. From that, one would say x is simply the reference.
x is the variable that binds the instance of Box<i32>, which is located in the stack, but it has some properties etc., and a heap pointer to the numeric result (the i32 value).
-
So is
xjust a reference that leads to its value when de-referenced, or what would be a good way to think about it (for a person newly introduced to Rust)? -
Or should I think of
xas a pointer to the start of the item in the stack? Or isxa Stack address? -
Or what?
2 posts - 2 participants
🏷️ rust_feed