Home
Rust
size_of, mem Example
Updated May 11, 2023
Dot Net Perls
Size of. In 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.
struct
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.
const Generic
Example. To begin we introduce 2 structs, Test and TestPacked. They both have the same contents, but TestPacked uses the packed repr to minimize padding.
packed
Step 1 We access the memory size of the Test struct. Note that no struct needs to be created in the program.
Step 2 We call size_of for TestPacked. This reveals its memory size is just 33 bytes versus 40 for Test.
Step 3 We compute the size of the fields of the 2 structs using 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.
vec
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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on May 11, 2023 (new).
Home
Changes
© 2007-2025 Sam Allen