This is an automated archive made by the Lemmit Bot.

The original was posted on /r/rust by /u/Abhi_3001 on 2025-05-08 06:25:27+00:00.


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! ❤️