Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix improper documentation on casting non_exhaustive enums #1607

Merged
merged 4 commits into from
Sep 10, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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