|
| 1 | +# `non_exhaustive` |
| 2 | + |
| 3 | +The tracking issue for this feature is: [#44109] |
| 4 | + |
| 5 | +[#44109]: https://github.com/rust-lang/rust/issues/44109 |
| 6 | + |
| 7 | +------------------------ |
| 8 | + |
| 9 | +The `non_exhaustive` gate allows you to use the `#[non_exhaustive]` attribute |
| 10 | +on structs and enums. When applied within a crate, users of the crate will need |
| 11 | +to use the `_` pattern when matching enums and use the `..` pattern when |
| 12 | +matching structs. Structs marked as `non_exhaustive` will not be able to be |
| 13 | +created normally outside of the defining crate. This is demonstrated below: |
| 14 | + |
| 15 | +```rust,ignore (pseudo-Rust) |
| 16 | +use std::error::Error as StdError; |
| 17 | +
|
| 18 | +#[non_exhaustive] |
| 19 | +pub enum Error { |
| 20 | + Message(String), |
| 21 | + Other, |
| 22 | +} |
| 23 | +impl StdError for Error { |
| 24 | + fn description(&self) -> &str { |
| 25 | + // This will not error, despite being marked as non_exhaustive, as this |
| 26 | + // enum is defined within the current crate, it can be matched |
| 27 | + // exhaustively. |
| 28 | + match *self { |
| 29 | + Message(ref s) => s, |
| 30 | + Other => "other or unknown error", |
| 31 | + } |
| 32 | + } |
| 33 | +} |
| 34 | +``` |
| 35 | + |
| 36 | +```rust,ignore (pseudo-Rust) |
| 37 | +use mycrate::Error; |
| 38 | +
|
| 39 | +// This will not error as the non_exhaustive Error enum has been matched with |
| 40 | +// a wildcard. |
| 41 | +match error { |
| 42 | + Message(ref s) => ..., |
| 43 | + Other => ..., |
| 44 | + _ => ..., |
| 45 | +} |
| 46 | +``` |
| 47 | + |
| 48 | +```rust,ignore (pseudo-Rust) |
| 49 | +#[non_exhaustive] |
| 50 | +pub struct Config { |
| 51 | + pub window_width: u16, |
| 52 | + pub window_height: u16, |
| 53 | +} |
| 54 | +
|
| 55 | +// We can create structs as normal within the defining crate when marked as |
| 56 | +// non_exhaustive. |
| 57 | +let config = Config { window_width: 640, window_height: 480 }; |
| 58 | +
|
| 59 | +// We can match structs exhaustively when within the defining crate. |
| 60 | +if let Ok(Config { window_width, window_height }) = load_config() { |
| 61 | + // ... |
| 62 | +} |
| 63 | +``` |
| 64 | + |
| 65 | +```rust,ignore (pseudo-Rust) |
| 66 | +use mycrate::Config; |
| 67 | +
|
| 68 | +// We cannot create a struct like normal if it has been marked as |
| 69 | +// non_exhaustive. |
| 70 | +let config = Config { window_width: 640, window_height: 480 }; |
| 71 | +// By adding the `..` we can match the config as below outside of the crate |
| 72 | +// when marked non_exhaustive. |
| 73 | +let &Config { window_width, window_height, .. } = config; |
| 74 | +``` |
| 75 | + |
0 commit comments