]> git.proxmox.com Git - rustc.git/blob - src/doc/unstable-book/src/language-features/non-exhaustive.md
New upstream version 1.35.0+dfsg1
[rustc.git] / src / doc / unstable-book / src / language-features / non-exhaustive.md
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, enums and enum variants. When applied within a crate, users of the
11 crate will need to use the `_` pattern when matching enums and use the `..`
12 pattern when matching structs. Enum variants cannot be matched against.
13 Structs and enum variants marked as `non_exhaustive` will not be able to
14 be created normally outside of the defining crate. This is demonstrated
15 below:
16
17 ```rust,ignore (pseudo-Rust)
18 use std::error::Error as StdError;
19
20 #[non_exhaustive]
21 pub enum Error {
22 Message(String),
23 Other,
24 }
25 impl StdError for Error {
26 fn description(&self) -> &str {
27 // This will not error, despite being marked as non_exhaustive, as this
28 // enum is defined within the current crate, it can be matched
29 // exhaustively.
30 match *self {
31 Message(ref s) => s,
32 Other => "other or unknown error",
33 }
34 }
35 }
36 ```
37
38 ```rust,ignore (pseudo-Rust)
39 use mycrate::Error;
40
41 // This will not error as the non_exhaustive Error enum has been matched with
42 // a wildcard.
43 match error {
44 Message(ref s) => ...,
45 Other => ...,
46 _ => ...,
47 }
48 ```
49
50 ```rust,ignore (pseudo-Rust)
51 #[non_exhaustive]
52 pub struct Config {
53 pub window_width: u16,
54 pub window_height: u16,
55 }
56
57 // We can create structs as normal within the defining crate when marked as
58 // non_exhaustive.
59 let config = Config { window_width: 640, window_height: 480 };
60
61 // We can match structs exhaustively when within the defining crate.
62 if let Ok(Config { window_width, window_height }) = load_config() {
63 // ...
64 }
65 ```
66
67 ```rust,ignore (pseudo-Rust)
68 use mycrate::Config;
69
70 // We cannot create a struct like normal if it has been marked as
71 // non_exhaustive.
72 let config = Config { window_width: 640, window_height: 480 };
73 // By adding the `..` we can match the config as below outside of the crate
74 // when marked non_exhaustive.
75 let &Config { window_width, window_height, .. } = config;
76 ```