Skip to content

ASCII art for structs #186

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Aug 29, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion reference/src/layout/structs-and-tuples.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,26 @@ struct Foo {
(In fact, one may use such field names in patterns or in accessor
expressions like `foo.0`.)

Structs can have various `#[repr]` flags that influence their layout:
The degrees of freedom the compiler has when computing the layout of a struct or
tuple is to determine the order of the fields, and the "gaps" (often called
*padding*) before, between, and after the fields. The layout of these fields
themselves is already entirely determined by their types, and since we intend to
allow creating references to fields (`&s.f1`), structs do not have any
wiggle-room there.

This can be visualized as follows:
```text
[ <--> [field 3] <-----> [field 1] <-> [ field 2 ] <--> ]
```
**Figure 1** (struct-field layout): The `<-...->` and `[ ... ]` denote the differently-sized gaps and fields, respectively.

Here, the individual fields are blocks of fixed size (determined by the field's
layout). The compiler freely picks an order for the fields to be in (this does
not have to be the order of declaration in the source), and it picks the gaps
between the fields (under some constraints, such as alignment).

How exactly the compiler picks order and gaps, as well as other aspects of
layout beyond size and field offset, can be controlled by a `#[repr]` attribute:

- `#[repr(Rust)]` -- the default.
- `#[repr(C)]` -- request C compatibility
Expand Down