@@ -81,9 +81,33 @@ consider passing in `0` as Undefined Behaviour.
81
81
82
82
Rust also enables types to be declared that * cannot even be instantiated* . These
83
83
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:
84
85
85
86
``` rust
86
- enum Foo { } // No variants = EMPTY
87
+ enum Void { } // No variants = EMPTY
87
88
```
88
89
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