Search⌘ K
AI Features

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.

Test it out

Hit “Run” to see the code’s output.

C++
use std::mem::size_of;
struct VeryImportantMessage {
_message_type : u8,
_destination : u16
}
fn main() {
println!(
"VeryImportantMessage occupies {} bytes.",
size_of::<VeryImportantMessage>()
);
}

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 ...