Why does &20 point to a static memory address while &x points to the stack?

54 points Abhi_3001 34 comments

Hey Rustaceans 👋,

I've been diving into how different data types and values are stored in memory, and I stumbled upon something interesting while playing with addresses.

Here is the example code.
```

    let x = 10;
    println!("x's address: {:p}", &x); // prints stack memory address
    let y = &20;
    println!("y's address: {:p}", y); // prints static memory address

```

Now, here's what surprised me:

  • &x gives me a stack address, as expected since x is a local variable.
  • But &20 gives me a static memory address! 🤯

It seems that when I directly reference a literal like &20, Rust is optimizing it by storing the value in static memory. I'm curious — is this some kind of compiler optimization or is it guaranteed behavior?

Would love to hear your thoughts or corrections! ❤️