Puzzle 14: Explanation
Explore Rust’s memory alignment and struct padding concepts in this lesson. Understand why Rust adds padding for performance, when it might cause issues, and how to use #[repr] attributes to control struct layout for FFI and memory efficiency.
We'll cover the following...
We'll cover the following...
Test it out
Hit “Run” to see the code’s output.
Explanation
Both _message_type and _destination occupy one and two bytes of memory. So, why does VeryImportantMessage occupy four bytes of memory?
By default, Rust makes these two promises about the in-memory representation of structures:
-
Structures may be differently sized than their contents for performance reasons.
-
Structures may internally store data in a different order than we specified if the optimizer ...