Home
Rust
packed Keyword (struct)
Updated May 11, 2023
Dot Net Perls
Repr packed. Consider a Rust program that must create many instances of a struct in memory. The size in bytes of each struct will begin to matter to the program's performance.
With repr packed, we can change the struct layout to be condensed for minimal memory usage. This can speed up (or slow down) programs.
struct
Example code. This program has 2 structs: the Node struct, and the NodePacked struct. The NodePacked struct uses the packed representation.
Info Each struct has a 4-byte id, and a 1-byte data member. The packed struct is 5 bytes, but the first struct is 8 bytes.
Tip The packed keyword saves 3 bytes per struct. Some structs, like those with pointers to the heap, should not be packed.
Tip 2 We invoke the size_of function from std mem to get the size of the structs in the program.
size_of
use std::mem; struct Node { id: u32, data: u8, } #[repr(packed)] struct NodePacked { id: u32, data: u8, } fn main() { println!("{}", mem::size_of::<NodePacked>()); println!("{}", mem::size_of::<Node>()); }
5 8
Performance notes. We can see a performance loss, or a performance gain with packed repr on a struct in Rust. Accesses to some fields will no longer be aligned, so they will slow down.
However More structs can be kept in memory at once, which reduces CPU cache misses.
So For actual programs, we need to test packed and benchmark it to see if it helps or not.
Also The order of fields in a packed struct can sometimes influence performance—this depends on how a field is aligned in memory.
Summary. With repr packed, we can adjust the memory usage of a Rust program. And with size_of, we can monitor memory usage changes and keep track of struct sizes.
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 (edit link).
Home
Changes
© 2007-2025 Sam Allen