[Avg. reading time: 4 minutes]
Memory Layout
How many bytes does a type actually occupy?
The std::mem::size_of::
use std::mem; fn main() { println!("i32 : {}", mem::size_of::<i32>()); println!("u32 : {}", mem::size_of::<u32>()); println!("f64 : {}", mem::size_of::<f64>()); println!("char : {}", mem::size_of::<char>()); println!("&str : {}", mem::size_of::<&str>()); println!("String : {}", mem::size_of::<String>()); }
| Type | Size (bytes) | Why |
|---|---|---|
i32 | 4 | 32 bits = 4 bytes |
u32 | 4 | 32 bits unsigned |
f64 | 8 | 64-bit float |
char | 4 | Unicode scalar value |
&str | 16 | pointer (8) + length (8) |
String | 24 | pointer (8) + length (8) + capacity (8) |
| Type | Stack Size | Heap Usage |
|---|---|---|
i32 | 4 | None |
f64 | 8 | None |
char | 4 | None |
&str | 16 | No Ownership |
String | 24 | Yes, for text |
- Primitive numeric types store values directly.
- &str is a pointer containing a memory address and length.
- String stores metadata on the stack but allocates its text on the heap.
String Literal points to location where Literal values are stored (Static Memory).
fn main(){ let s = "Rachel"; println!("{},{:p}", s, s.as_ptr()) }