A Rust Programming Puzzle

Rust Structure Packing

How Can We Control Structure Layout?

Herbert Wolverson
The Pragmatic Programmers
3 min readJul 20, 2021

--

Let’s see what you already know about structures in Rust and how the compiler handles them.

See if you can guess the output from the following program:

Click here to run the program on the Rust Playground.

Result

You may be surprised by the result:

OneByte occupies 1 bytes.
TwoBytes occupies 2 bytes.
ThreeBytes occupies 4 bytes.

The OneByte and TwoBytes structures are occupying 1- and 2-bytes of memory — as you would expect. ThreeBytes has only 3-bytes of data but reports a size of 4 bytes.

Discussion

By default, Rust makes no promises about the layout of structures, other than your variables will be included inside them. In particular, the Rust/LLVM toolchain (the compiler system Rust uses) is free to make two changes to your structures if it determines that they will help performance:

--

--