Skip to content

Commit a826357

Browse files
committed
Only propagate repr(C); show how to write repr(packed) explicitly
1 parent 9e2f5f0 commit a826357

File tree

1 file changed

+36
-10
lines changed

1 file changed

+36
-10
lines changed

text/0000-unnamed-fields.md

Lines changed: 36 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -342,16 +342,42 @@ This feature exists to support the layout of native platform data structures.
342342
Structures using the default `repr(Rust)` layout cannot use this feature, and
343343
the compiler should produce an error when attempting to do so.
344344

345-
When using this mechanism to define a C interface, remember to use the
346-
`repr(C)` attribute to match C's data structure layout. Any representation
347-
attribute applied to the top-level structure also applies to every unnamed
348-
field within that declaration. Such a structure defined with `repr(C)` will use
349-
a representation identical to the same structure with all unnamed fields
350-
transformed to equivalent named fields of a struct or union type with the same
351-
fields.
352-
353-
Similarly, applying `repr(packed)` to the top-level data structure will also
354-
apply it to all the contained structures.
345+
When using this mechanism to define a C interface, always use the `repr(C)`
346+
attribute to match C's data structure layout. For convenience, `repr(C)`
347+
applied to the top-level structure will automatically apply to every unnamed
348+
struct within that declaration, since unnamed fields only permit `repr(C)`.
349+
This only applies to `repr(C)`, not to any other attribute.
350+
351+
Such a structure defined with `repr(C)` will use a representation identical to
352+
the same structure with all unnamed fields transformed to equivalent named
353+
fields of a struct or union type with the same fields.
354+
355+
However, applying `repr(packed)` (or any other attribute) to the top-level data
356+
structure does not automatically apply it to all the contained structures. To
357+
apply `repr(packed)` to an unnamed field, place the attribute before the field
358+
declaration:
359+
360+
```rust
361+
#[repr(C)]
362+
union S {
363+
a: u32,
364+
#[repr(packed)]
365+
_: struct {
366+
b: u8,
367+
c: u16,
368+
},
369+
_: struct {
370+
d: u8,
371+
e: f16,
372+
},
373+
}
374+
```
375+
376+
In this declaration, the first unnamed struct uses `repr(packed)`, while the
377+
second does not.
378+
379+
Unnamed fields with named types use the representation attributes attached to
380+
the named type. The named type must use `repr(C)`.
355381

356382
## Derive
357383

0 commit comments

Comments
 (0)