Skip to content

Commit 42c2f10

Browse files
committed
flesh out void types
1 parent 94a89e5 commit 42c2f10

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

src/doc/tarpl/exotic-sizes.md

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,9 +81,33 @@ consider passing in `0` as Undefined Behaviour.
8181

8282
Rust also enables types to be declared that *cannot even be instantiated*. These
8383
types can only be talked about at the type level, and never at the value level.
84+
Empty types can be declared by specifying an enum with no variants:
8485

8586
```rust
86-
enum Foo { } // No variants = EMPTY
87+
enum Void {} // No variants = EMPTY
8788
```
8889

89-
TODO: WHY?!
90+
Empty types are even more marginal than ZSTs. The primary motivating example for
91+
Void types is type-level unreachability. For instance, suppose an API needs to
92+
return a Result in general, but a specific case actually is infallible. It's
93+
actually possible to communicate this at the type level by returning a
94+
`Result<T, Void>`. Consumers of the API can confidently unwrap such a Result
95+
knowing that it's *statically impossible* for this value to be an `Err`, as
96+
this would require providing a value of type Void.
97+
98+
In principle, Rust can do some interesting analysees and optimizations based
99+
on this fact. For instance, `Result<T, Void>` could be represented as just `T`,
100+
because the Err case doesn't actually exist. Also in principle the following
101+
could compile:
102+
103+
```rust,ignore
104+
enum Void {}
105+
106+
let res: Result<u32, Void> = Ok(0);
107+
108+
// Err doesn't exist anymore, so Ok is actually irrefutable.
109+
let Ok(num) = res;
110+
```
111+
112+
But neither of these tricks work today, so all Void types get you today is
113+
the ability to be confident that certain situations are statically impossible.

0 commit comments

Comments
 (0)