Related: rust, systems-programming, Demystifying Alignment and Memory Layout in Rust


Here’s a list of exercises to test your understanding of memory alignment and layout for various types, some of which are Rust specific. The assumption for this exercise is that the Rust-style representation (#[repr(Rust)]) is used.

Info

If you’re unfamiliar with the concept of alignment and memory layout, or simply need a refresher, read my write-up on it.

Stretch 🙆‍♂️

Walk 🚶

Given the following struct:

struct User {
    age: u32,
    name: String,
    english_native_lang: bool
}

Given

enum SpaceShuttleStatus {
    OnGround,
    Launched { elevation: u64 },
    Docked,
}

Run 🏃

struct Astronaut {
    name: String,
    age: u32
}
 
enum SpaceShuttleStatus {
    OnGround,
    Launched { elevation: u64},
    Docked,
}
 
struct SpaceShuttleFlight {
    id: String,
    status: SpaceShuttleStatus,
    passengers: Vec<Astronaut>
}

Footnotes

  1. UTF-8 is a variable-width encoding—a character may span between 1 and 4 bytes. Storing them as u8 is more efficient than #[repr(transparent)] which takes up 4 bytes.

  2. This is a real-life human response, not a ChainOfThought response from a chatbot 😆

  3. For fields of the same size, the Rust compiler doesn’t provide guarantees on which field’s data goes first.