Skip to content

Commit 636d140

Browse files
authored
Merge pull request #186 from RalfJung/structs
ASCII art for structs
2 parents fcfb77d + cdf1259 commit 636d140

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

reference/src/layout/structs-and-tuples.md

+20-1
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,26 @@ struct Foo {
7272
(In fact, one may use such field names in patterns or in accessor
7373
expressions like `foo.0`.)
7474

75-
Structs can have various `#[repr]` flags that influence their layout:
75+
The degrees of freedom the compiler has when computing the layout of a struct or
76+
tuple is to determine the order of the fields, and the "gaps" (often called
77+
*padding*) before, between, and after the fields. The layout of these fields
78+
themselves is already entirely determined by their types, and since we intend to
79+
allow creating references to fields (`&s.f1`), structs do not have any
80+
wiggle-room there.
81+
82+
This can be visualized as follows:
83+
```text
84+
[ <--> [field 3] <-----> [field 1] <-> [ field 2 ] <--> ]
85+
```
86+
**Figure 1** (struct-field layout): The `<-...->` and `[ ... ]` denote the differently-sized gaps and fields, respectively.
87+
88+
Here, the individual fields are blocks of fixed size (determined by the field's
89+
layout). The compiler freely picks an order for the fields to be in (this does
90+
not have to be the order of declaration in the source), and it picks the gaps
91+
between the fields (under some constraints, such as alignment).
92+
93+
How exactly the compiler picks order and gaps, as well as other aspects of
94+
layout beyond size and field offset, can be controlled by a `#[repr]` attribute:
7695

7796
- `#[repr(Rust)]` -- the default.
7897
- `#[repr(C)]` -- request C compatibility

0 commit comments

Comments
 (0)