Home
Rust
size_of, mem Example
This page was last reviewed on 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 11, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.