Size
ofIn Rust we can easily access the number of bytes required for a type (like a struct
or usize
). The mem size_of
function helps here.
With this function, we use a type argument with const
generic syntax. This is the TurboFish operator (which specifies a type). Size_of
is evaluated at compile-time.
To begin we introduce 2 structs, Test and TestPacked
. They both have the same contents, but TestPacked
uses the packed repr to minimize padding.
struct
. Note that no struct
needs to be created in the program.size_of
for TestPacked
. This reveals its memory size is just 33 bytes versus 40 for Test.size_of
as well. Each call can be computed at compile-time.use std::mem; struct Test { valid: bool, length: usize, items: Vec<u8>, } #[repr(packed)] struct TestPacked { valid: bool, length: usize, items: Vec<u8>, } fn main() { // Step 1: get size of Test struct. println!("Test = {} bytes", mem::size_of::<Test>()); // Step 2: size of TestPacked struct (with repr packed). println!("TestPacked = {} bytes", mem::size_of::<TestPacked>()); // Step 3: print sizes of the fields of Test and TestPacked. println!("Bool = {} bytes", mem::size_of::<bool>()); println!("Usize = {} bytes", mem::size_of::<usize>()); println!("Vec = {} bytes", mem::size_of::<Vec<u8>>()); }Test = 40 bytes TestPacked = 33 bytes Bool = 1 bytes Usize = 8 bytes Vec = 24 bytes
For vectors, we have 24 bytes for the reference. This is 3 words (at 8 bytes per word) and these are for the length, capacity, and the memory location of elements.
For calculating sizes of structs, size_of
is useful. It uses const
generic syntax (TurboFish style) which can be confusing at first, but can be memorized.