this post was submitted on 28 Apr 2026
9 points (80.0% liked)
Rust
7969 readers
23 users here now
Welcome to the Rust community! This is a place to discuss about the Rust programming language.
Wormhole
Credits
- The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)
founded 2 years ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
Yes, except rust has even stricter requirements - namely that your struct must only contain the "inherited" field and you still need to tell the rust compiler to use the special
#[repr(transparent)]!This is because the compiler is allowed - under "normal" representation rules - to rearrange basically everything about the memory layout of a struct to better suit its needs. And as far as I know this includes rearranging the location of a field which is arbitrarily deep inside other structures in your struct! As such
could theoretically be laid out as
bar test foo- as opposed to e.g.foo barfor just A - in memory if the compiler determined that accessing bar at the start of the struct was overall the "best".If, on the other hand, you use
#[repr(c)]you get exactly what you just said, although the direct casting may or may not be undefined still. (I currently do not remember the relevant parts of the nomicon or other treaties I have read about this... I really need to get back into programming rust at some point!)Quick edit: Expanded the possible memory layout of just the struct A.