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 2 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
29 changes: 25 additions & 4 deletions src/attributes/type_system.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,12 +163,33 @@ match message {
}
```

It's also not allowed to cast non-exhaustive types from foreign crates.
However, casting non-exhaustive types from foreign crates is generally disallowed, except when dealing with enums that have no non-exhaustive variants.
mixy1 marked this conversation as resolved.
Show resolved Hide resolved

For example, the following enum can be cast because it doesn't contain any non-exhaustive variants:
```rust, ignore
#[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, ignore
#[non_exhaustive]
pub enum Example {
First,
#[non_exhaustive]
Second
}
```

```rust, ignore
use othercrate::NonExhaustiveEnum;
use othercrate::EnumWithNonExhaustiveEnumVariants;

// 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 _ = EnumWithNonExhaustiveEnumVariants::default() as u8;
```

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