Skip to content

Commit 054361b

Browse files
authored
Merge pull request #2 from RalfJung/single_field_struct
rearrange a bit and be more explicit about how our rules interact
2 parents 51f0ec0 + 1883271 commit 054361b

File tree

1 file changed

+33
-19
lines changed

1 file changed

+33
-19
lines changed

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

+33-19
Original file line numberDiff line numberDiff line change
@@ -124,28 +124,11 @@ compiler will not reorder it, to allow for the possibility of
124124
unsizing. E.g., `struct Foo { x: u16, y: u32 }` and `struct Foo<T> {
125125
x: u16, y: T }` where `T = u32` are not guaranteed to be identical.
126126

127-
#### Structs with 1-ZST fields
128-
129-
For the purposes of struct layout [1-ZST] fields are ignored.
130-
131-
For example:
132-
133-
```rust
134-
type Zst1 = ();
135-
struct S1(i32, Zst1); // same layout as i32
136-
137-
type Zst2 = [u16; 0];
138-
struct S2(Zst2, Zst1); // same layout as Zst2
139-
140-
struct S3(Zst1); // same layout as Zst1
141-
```
142-
143127
#### Zero-sized structs
128+
[zero-sized structs]: #zero-sized-structs
144129

145130
For `repr(Rust)`, `repr(packed(N))`, `repr(align(N))`, and `repr(C)` structs: if
146-
all fields of a struct have size 0, then the struct has size 0. In particular, a
147-
struct with no fields is a ZST, and if it has no repr attribute it is moreover a
148-
1-ZST as it also has no alignment requirements.
131+
all fields of a struct have size 0, then the struct has size 0.
149132

150133
For example, all these types are zero-sized:
151134

@@ -161,6 +144,37 @@ struct Zst2(Zst1, Zst0);
161144
# }
162145
```
163146

147+
In particular, a struct with no fields is a ZST, and if it has no repr attribute
148+
it is moreover a 1-ZST as it also has no alignment requirements.
149+
150+
#### Single-field structs
151+
[single-field structs]: #single-field-structs
152+
153+
A struct with only one field has the same layout as that field.
154+
155+
#### Structs with 1-ZST fields
156+
157+
For the purposes of struct layout [1-ZST] fields are ignored.
158+
159+
In particular, if all but one field are 1-ZST, then the struct is equivalent to
160+
a [single-field struct][single-field structs]. In other words, if all but one
161+
field is a 1-ZST, then the entire struct has the same layout as that one field.
162+
163+
Similarly, if all fields are 1-ZST, then the struct has the same layout as a
164+
[struct with no fields][zero-sized structs], and is itself a 1-ZST.
165+
166+
For example:
167+
168+
```rust
169+
type Zst1 = ();
170+
struct S1(i32, Zst1); // same layout as i32
171+
172+
type Zst2 = [u16; 0];
173+
struct S2(Zst2, Zst1); // same layout as Zst2
174+
175+
struct S3(Zst1); // same layout as Zst1
176+
```
177+
164178
#### Unresolved questions
165179

166180
During the course of the discussion in [#11] and [#12], various

0 commit comments

Comments
 (0)