Skip to content

Commit

Permalink
Merge pull request #1607 from mixy1/patch-1
Browse files Browse the repository at this point in the history
Fix improper documentation on casting non_exhaustive enums
  • Loading branch information
ehuss authored Sep 10, 2024
2 parents 687faf9 + 7c94f29 commit 06eb669
Showing 1 changed file with 28 additions and 5 deletions.
33 changes: 28 additions & 5 deletions src/attributes/type_system.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,12 +163,35 @@ match message {
}
```

It's also not allowed to cast non-exhaustive types from foreign crates.
```rust, ignore
use othercrate::NonExhaustiveEnum;
It's also not allowed to use numeric casts (`as`) on enums that contain any non-exhaustive variants.

For example, the following enum can be cast because it doesn't contain any non-exhaustive variants:

```rust
#[non_exhaustive]
pub enum Example {
First,
Second
}
```

However, if the enum contains even a single non-exhaustive variant, casting will result in an error. Consider this modified version of the same enum:

```rust
#[non_exhaustive]
pub enum EnumWithNonExhaustiveVariants {
First,
#[non_exhaustive]
Second
}
```

<!-- ignore: needs multiple crates -->
```rust,ignore
use othercrate::EnumWithNonExhaustiveVariants;
// Cannot cast a non-exhaustive enum outside of its defining crate.
let _ = NonExhaustiveEnum::default() as u8;
// Error: cannot cast an enum with a non-exhaustive variant when it's defined in another crate
let _ = EnumWithNonExhaustiveVariants::First as u8;
```

Non-exhaustive types are always considered inhabited in downstream crates.
Expand Down

0 comments on commit 06eb669

Please sign in to comment.