|
1 |
| -When defining a recursive struct or enum, any use of the type being defined |
2 |
| -from inside the definition must occur behind a pointer (like `Box` or `&`). |
3 |
| -This is because structs and enums must have a well-defined size, and without |
4 |
| -the pointer, the size of the type would need to be unbounded. |
| 1 | +A recursive type has infinite size because it doesn't have an indirection. |
5 | 2 |
|
6 |
| -Consider the following erroneous definition of a type for a list of bytes: |
| 3 | +Erroneous code example: |
7 | 4 |
|
8 | 5 | ```compile_fail,E0072
|
9 |
| -// error, invalid recursive struct type |
10 | 6 | struct ListNode {
|
11 | 7 | head: u8,
|
12 |
| - tail: Option<ListNode>, |
| 8 | + tail: Option<ListNode>, // error: no indirection here so impossible to |
| 9 | + // compute the type's size |
13 | 10 | }
|
14 | 11 | ```
|
15 | 12 |
|
16 |
| -This type cannot have a well-defined size, because it needs to be arbitrarily |
17 |
| -large (since we would be able to nest `ListNode`s to any depth). Specifically, |
| 13 | +When defining a recursive struct or enum, any use of the type being defined |
| 14 | +from inside the definition must occur behind a pointer (like `Box`, `&` or |
| 15 | +`Rc`). This is because structs and enums must have a well-defined size, and |
| 16 | +without the pointer, the size of the type would need to be unbounded. |
| 17 | + |
| 18 | +In the example, the type cannot have a well-defined size, because it needs to be |
| 19 | +arbitrarily large (since we would be able to nest `ListNode`s to any depth). |
| 20 | +Specifically, |
18 | 21 |
|
19 | 22 | ```plain
|
20 | 23 | size of `ListNode` = 1 byte for `head`
|
|
0 commit comments