In Rust, why mark a newtype like `struct Pid(c_int)` `#[repr(transparent)]` rather than `#[repr(C)]` before passing it to C as an int, and what fields may it hold?
answer
- same layout is not same ABI
- the wrapper disappears at the call
- one non-trivial field
- zero-sized, alignment-1 extras only
basics
~20 srepr(transparent) gives the newtype the same layout and ABI as its single non-trivial field, so C sees a plain int. repr(C) only promises a C struct's layout and ABI. Other fields must be size 0, alignment 1, like PhantomData.
solid answer
~50 s`#[repr(transparent)]` promises that the wrapper has the **same layout and ABI** as its one non-trivial field, so a `Pid` is passed and returned exactly like the `c_int` inside it, and `&[Pid]` can be read as `&[c_int]`. `#[repr(C)]` on a one-field struct gives the same size and alignment but the ABI of a C struct, which some calling conventions pass differently from a bare integer; the Reference draws exactly that distinction. The attribute allows at most one field that is not zero-sized with alignment 1; extra fields must be markers like `PhantomData<T>`, and rustc rejects anything else with E0690. Since Rust 1.98 the check is stricter: a `#[repr(C)]` zero-sized type, a type with private fields from another crate, or a `#[non_exhaustive]` type no longer counts as trivial. A transparent wrapper also keeps the `Option` niche guarantee of its inner type.
code
rust · 23 linesuse std::ffi::c_int;
/// A process id: same layout and ABI as C's `int`.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq)]
struct Pid(c_int);
unsafe extern "C" {
// C declares `int getpid(void);` and Rust receives it as a Pid.
safe fn getpid() -> Pid;
}
fn main() {
let me = getpid();
println!("pid {:?}", me);
// repr(transparent) also makes a slice of Pid readable as a slice of c_int.
let pids = [me, Pid(1)];
let raw: &[c_int] =
unsafe { std::slice::from_raw_parts(pids.as_ptr().cast::<c_int>(), pids.len()) };
assert_eq!(raw[1], 1);
assert_eq!(size_of::<Pid>(), size_of::<c_int>());
}go deeper
Recall that repr(transparent) makes a one-field wrapper identical to its field, so it can stand in for that field at a C boundary.
Explain the difference between layout and ABI, and the field rule: one non-trivial field plus any size-0, alignment-1 markers.
Show where the guarantee is load-bearing (an extern fn signature, a slice cast, an Option niche) and diagnose E0690, including the 1.98 rule on repr(C), private-field and non_exhaustive types.
Decide which public types promise a transparent layout: once documented it is part of the API, so keep the field private when the layout is an implementation detail.
## The scenario A process id comes back from C as `int`, and the team wants a distinct Rust type so a pid cannot be confused with a file descriptor or a count. The newtype is `struct Pid(c_int)`. Whether that wrapper can cross the C boundary depends entirely on its representation. ## Layout versus ABI Two different promises are involved: - **Layout** is size, alignment and field offsets. In practice `Pid` is 4 bytes with alignment 4 under any representation, but the default one promises nothing; `#[repr(C)]` and `#[repr(transparent)]` both promise it. - **ABI** is how a value travels through a function call: in which register or stack slot, and whether as an integer or as an aggregate. A calling convention may treat "a struct containing one `int`" differently from "an `int`". The Reference states the difference: a struct with the C representation "will always have the ABI of a C struct", while a transparent struct with a primitive field "will have the ABI of the primitive field". So for `extern "C" fn getpid() -> Pid`, only `#[repr(transparent)]` makes `Pid` match a C declaration that returns `int`. Declaring and calling C functions is covered with foreign function calls; the layout promise is what this lesson owns. ## What `#[repr(transparent)]` guarantees The Reference's rule: a struct, or an enum with a single variant, may be transparent when it has 1. **at most one** field that is not trivial, and 2. any number of fields with **size 0 and alignment 1**, such as `PhantomData<T>`. The type then has the same layout and ABI as that one non-trivial field, or of `()` if there is none. Because it delegates its layout, it cannot be combined with another representation; rustc rejects `#[repr(transparent, packed)]` with E0692, "transparent struct cannot have other repr hints". Practical consequences: - **Pointer casts become sound.** `&Pid` to `&c_int`, and a `&[Pid]` read as `&[c_int]` through `slice::from_raw_parts`, are valid because the two types are laid out identically. - **Marker parameters are free.** `struct Meters<Unit> { value: f64, _unit: PhantomData<Unit> }` is still exactly an `f64`. - **Niches carry over.** The `core::option` representation guarantee lists "a `#[repr(transparent)]` struct around" `&T`, `Box<T>`, `NonNull<T>`, a function pointer or a `NonZero` integer, so `Option` of such a wrapper is as small as the wrapper. - std uses it too, for example on `std::cmp::Reverse`. ## What counts as trivial, and the 1.98 change | Extra field | Accepted by rustc 1.99.1? | Reason | |---|---|---| | `PhantomData<String>` | yes | size 0, alignment 1 | | a second `u32` | no, E0690 | non-zero size | | `[u16; 0]` | no, E0690 | size 0 but alignment 2 | | a `#[repr(C)]` unit struct | no, E0690 since 1.98 | rustc: "not guaranteed to be zero-sized on all targets" | | another crate's struct with private fields, even if empty | no, E0690 since 1.98 | it "could become non-zero-sized in the future" | | another crate's `#[non_exhaustive]` struct | no, E0690 since 1.98 | the same reason | The error reads "transparent struct needs at most one non-trivial field, but has 2", and rustc labels the offending field with its reason. Rust 1.93 introduced a future-compatibility warning for ignoring `repr(C)` types inside `repr(transparent)`; Rust 1.98 made the stricter rule a hard error and extended it to private-field and `#[non_exhaustive]` types. The reason is semver: a library may add a private field to a type it exported as empty, and your wrapper's ABI must not change when it does. ## Choosing between the two attributes - **`#[repr(transparent)]`** when the wrapper must *be* its field at a boundary: an FFI argument or return value, a pointer cast, a transmute, an `Option` niche you depend on. - **`#[repr(C)]`** when the type really is a C struct, typically with several fields, and the C side declares it as a struct. - **Neither** for an ordinary newtype that never leaves Rust; the default representation is fine. ## Keeping the wrapper honest The attribute guarantees layout, not meaning. If `Pid` has a public field, any `c_int` can become a `Pid`; whether invalid values matter is a soundness question for the safe API, covered with sound safe abstractions. rustdoc hides the attribute from generated docs when it is not part of the public ABI, for example when the field is private.
- Can a `#[repr(transparent)]` struct have no non-trivial field at all, and what is its layout then?Yes. A transparent struct whose only fields are zero-sized with alignment 1, such as a lone `PhantomData<T>`, is accepted, and the Reference says its layout and ABI are then those of `()`: size 0, alignment 1.
- Why does `Option<Handle>` stay pointer-sized when `struct Handle(NonNull<u8>)` is `#[repr(transparent)]`?The `core::option` docs list a `#[repr(transparent)]` struct around `NonNull<U>` among the types whose `Option` has the same size, alignment and ABI. The wrapper inherits the never-null niche, so `None` is the null pointer and C can receive `Option<Handle>` as a nullable pointer.
- repr(C) on a one-field struct gives the same ABI as the field
- repr(transparent) allows several fields as long as they are small
- Any zero-sized field is allowed beside the real one
- A newtype without a repr attribute is guaranteed to match its field
- repr(transparent) can be combined with repr(C) for extra safety
Assumes Rust 1.99 on edition 2024; Rust 1.98 stopped treating repr(C) zero-sized types, other crates' types with private fields and non_exhaustive types as trivial fields of a repr(transparent) type.