To begin we introduce 2 structs, Test and TestPacked. They both have the same contents, but TestPacked uses the packed repr to minimize padding.
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