std/
keyword_docs.rs

1#[doc(keyword = "as")]
2//
3/// Cast between types, rename an import, or qualify paths to associated items.
4///
5/// # Type casting
6///
7/// `as` is most commonly used to turn primitive types into other primitive types, but it has other
8/// uses that include turning pointers into addresses, addresses into pointers, and pointers into
9/// other pointers.
10///
11/// ```rust
12/// let thing1: u8 = 89.0 as u8;
13/// assert_eq!('B' as u32, 66);
14/// assert_eq!(thing1 as char, 'Y');
15/// let thing2: f32 = thing1 as f32 + 10.5;
16/// assert_eq!(true as u8 + thing2 as u8, 100);
17/// ```
18///
19/// In general, any cast that can be performed via ascribing the type can also be done using `as`,
20/// so instead of writing `let x: u32 = 123`, you can write `let x = 123 as u32` (note: `let x: u32
21/// = 123` would be best in that situation). The same is not true in the other direction, however;
22/// explicitly using `as` allows a few more coercions that aren't allowed implicitly, such as
23/// changing the type of a raw pointer or turning closures into raw pointers.
24///
25/// `as` can be seen as the primitive for `From` and `Into`: `as` only works  with primitives
26/// (`u8`, `bool`, `str`, pointers, ...) whereas `From` and `Into`  also works with types like
27/// `String` or `Vec`.
28///
29/// `as` can also be used with the `_` placeholder when the destination type can be inferred. Note
30/// that this can cause inference breakage and usually such code should use an explicit type for
31/// both clarity and stability. This is most useful when converting pointers using `as *const _` or
32/// `as *mut _` though the [`cast`][const-cast] method is recommended over `as *const _` and it is
33/// [the same][mut-cast] for `as *mut _`: those methods make the intent clearer.
34///
35/// # Renaming imports
36///
37/// `as` is also used to rename imports in [`use`] and [`extern crate`][`crate`] statements:
38///
39/// ```
40/// # #[allow(unused_imports)]
41/// use std::{mem as memory, net as network};
42/// // Now you can use the names `memory` and `network` to refer to `std::mem` and `std::net`.
43/// ```
44///
45/// # Qualifying paths
46///
47/// You'll also find with `From` and `Into`, and indeed all traits, that `as` is used for the
48/// _fully qualified path_, a means of disambiguating associated items, i.e. functions,
49/// constants, and types.  For example, if you have a type which implements two traits with identical
50/// method names (e.g. `Into::<u32>::into` and `Into::<u64>::into`), you can clarify which method
51/// you'll use with `<MyThing as Into<u32>>::into(my_thing)`[^as-use-from].  This is quite verbose,
52/// but fortunately, Rust's type inference usually saves you from needing this, although it is
53/// occasionally necessary, especially with methods that return a generic type like `Into::into` or
54/// methods that don't take `self`.  It's more common to use in macros where it can provide necessary
55/// hygiene.
56///
57/// [^as-use-from]: You should probably never use this syntax with `Into` and instead write
58/// `T::from(my_thing)`.  It just happens that there aren't any great examples for this syntax in
59/// the standard library.  Also, at time of writing, the compiler tends to suggest fully-qualified
60/// paths to fix ambiguous `Into::into` calls, so the example should hopefully be familiar.
61///
62/// # Further reading
63///
64/// For more information on what `as` is capable of, see the Reference on [type cast expressions],
65/// [renaming imported entities], [renaming `extern` crates]
66/// and [qualified paths].
67///
68/// [type cast expressions]: ../reference/expressions/operator-expr.html#type-cast-expressions
69/// [renaming imported entities]: https://doc.rust-lang.org/reference/items/use-declarations.html#as-renames
70/// [renaming `extern` crates]: https://doc.rust-lang.org/reference/items/extern-crates.html#r-items.extern-crate.as
71/// [qualified paths]: ../reference/paths.html#qualified-paths
72/// [`crate`]: keyword.crate.html
73/// [`use`]: keyword.use.html
74/// [const-cast]: pointer::cast
75/// [mut-cast]: primitive.pointer.html#method.cast-1
76mod as_keyword {}
77
78#[doc(keyword = "break")]
79//
80/// Exit early from a loop or labelled block.
81///
82/// When `break` is encountered, execution of the associated loop body is
83/// immediately terminated.
84///
85/// ```rust
86/// let mut last = 0;
87///
88/// for x in 1..100 {
89///     if x > 12 {
90///         break;
91///     }
92///     last = x;
93/// }
94///
95/// assert_eq!(last, 12);
96/// println!("{last}");
97/// ```
98///
99/// A break expression is normally associated with the innermost loop enclosing the
100/// `break` but a label can be used to specify which enclosing loop is affected.
101///
102/// ```rust
103/// 'outer: for i in 1..=5 {
104///     println!("outer iteration (i): {i}");
105///
106///     '_inner: for j in 1..=200 {
107///         println!("    inner iteration (j): {j}");
108///         if j >= 3 {
109///             // breaks from inner loop, lets outer loop continue.
110///             break;
111///         }
112///         if i >= 2 {
113///             // breaks from outer loop, and directly to "Bye".
114///             break 'outer;
115///         }
116///     }
117/// }
118/// println!("Bye.");
119/// ```
120///
121/// When associated with `loop`, a break expression may be used to return a value from that loop.
122/// This is only valid with `loop` and not with any other type of loop.
123/// If no value is specified for `break;` it returns `()`.
124/// Every `break` within a loop must return the same type.
125///
126/// ```rust
127/// let (mut a, mut b) = (1, 1);
128/// let result = loop {
129///     if b > 10 {
130///         break b;
131///     }
132///     let c = a + b;
133///     a = b;
134///     b = c;
135/// };
136/// // first number in Fibonacci sequence over 10:
137/// assert_eq!(result, 13);
138/// println!("{result}");
139/// ```
140///
141/// It is also possible to exit from any *labelled* block returning the value early.
142/// If no value is specified for `break;` it returns `()`.
143///
144/// ```rust
145/// let inputs = vec!["Cow", "Cat", "Dog", "Snake", "Cod"];
146///
147/// let mut results = vec![];
148/// for input in inputs {
149///     let result = 'filter: {
150///         if input.len() > 3 {
151///             break 'filter Err("Too long");
152///         };
153///
154///         if !input.contains("C") {
155///             break 'filter Err("No Cs");
156///         };
157///
158///         Ok(input.to_uppercase())
159///     };
160///
161///     results.push(result);
162/// }
163///
164/// // [Ok("COW"), Ok("CAT"), Err("No Cs"), Err("Too long"), Ok("COD")]
165/// println!("{:?}", results)
166/// ```
167///
168/// For more details consult the [Reference on "break expression"] and the [Reference on "break and
169/// loop values"].
170///
171/// [Reference on "break expression"]: ../reference/expressions/loop-expr.html#break-expressions
172/// [Reference on "break and loop values"]:
173/// ../reference/expressions/loop-expr.html#break-and-loop-values
174mod break_keyword {}
175
176#[doc(keyword = "const")]
177//
178/// Compile-time constants, compile-time blocks, compile-time evaluable functions, and raw pointers.
179///
180/// ## Compile-time constants
181///
182/// Sometimes a certain value is used many times throughout a program, and it can become
183/// inconvenient to copy it over and over. What's more, it's not always possible or desirable to
184/// make it a variable that gets carried around to each function that needs it. In these cases, the
185/// `const` keyword provides a convenient alternative to code duplication:
186///
187/// ```rust
188/// const THING: u32 = 0xABAD1DEA;
189///
190/// let foo = 123 + THING;
191/// ```
192///
193/// Constants must be explicitly typed; unlike with `let`, you can't ignore their type and let the
194/// compiler figure it out. Any constant value can be defined in a `const`, which in practice happens
195/// to be most things that would be reasonable to have in a constant (barring `const fn`s). For
196/// example, you can't have a [`File`] as a `const`.
197///
198/// [`File`]: crate::fs::File
199///
200/// The only lifetime allowed in a constant is `'static`, which is the lifetime that encompasses
201/// all others in a Rust program. For example, if you wanted to define a constant string, it would
202/// look like this:
203///
204/// ```rust
205/// const WORDS: &'static str = "hello rust!";
206/// ```
207///
208/// Thanks to static lifetime elision, you usually don't have to explicitly use `'static`:
209///
210/// ```rust
211/// const WORDS: &str = "hello convenience!";
212/// ```
213///
214/// `const` items look remarkably similar to `static` items, which introduces some confusion as
215/// to which one should be used at which times. To put it simply, constants are inlined wherever
216/// they're used, making using them identical to simply replacing the name of the `const` with its
217/// value. Static variables, on the other hand, point to a single location in memory, which all
218/// accesses share. This means that, unlike with constants, they can't have destructors, and act as
219/// a single value across the entire codebase.
220///
221/// Constants, like statics, should always be in `SCREAMING_SNAKE_CASE`.
222///
223/// For more detail on `const`, see the [Rust Book] or the [Reference].
224///
225/// ## Compile-time blocks
226///
227/// The `const` keyword can also be used to define a block of code that is evaluated at compile time.
228/// This is useful for ensuring certain computations are completed before optimizations happen, as well as
229/// before runtime. For more details, see the [Reference][const-blocks].
230///
231/// ## Compile-time evaluable functions
232///
233/// The other main use of the `const` keyword is in `const fn`. This marks a function as being
234/// callable in the body of a `const` or `static` item and in array initializers (commonly called
235/// "const contexts"). `const fn` are restricted in the set of operations they can perform, to
236/// ensure that they can be evaluated at compile-time. See the [Reference][const-eval] for more
237/// detail.
238///
239/// Turning a `fn` into a `const fn` has no effect on run-time uses of that function.
240///
241/// ## Other uses of `const`
242///
243/// The `const` keyword is also used in raw pointers in combination with `mut`, as seen in `*const
244/// T` and `*mut T`. More about `const` as used in raw pointers can be read at the Rust docs for the [pointer primitive].
245///
246/// [pointer primitive]: pointer
247/// [Rust Book]: ../book/ch03-01-variables-and-mutability.html#constants
248/// [Reference]: ../reference/items/constant-items.html
249/// [const-blocks]: ../reference/expressions/block-expr.html#const-blocks
250/// [const-eval]: ../reference/const_eval.html
251mod const_keyword {}
252
253#[doc(keyword = "continue")]
254//
255/// Skip to the next iteration of a loop.
256///
257/// When `continue` is encountered, the current iteration is terminated, returning control to the
258/// loop head, typically continuing with the next iteration.
259///
260/// ```rust
261/// // Printing odd numbers by skipping even ones
262/// for number in 1..=10 {
263///     if number % 2 == 0 {
264///         continue;
265///     }
266///     println!("{number}");
267/// }
268/// ```
269///
270/// Like `break`, `continue` is normally associated with the innermost enclosing loop, but labels
271/// may be used to specify the affected loop.
272///
273/// ```rust
274/// // Print Odd numbers under 30 with unit <= 5
275/// 'tens: for ten in 0..3 {
276///     '_units: for unit in 0..=9 {
277///         if unit % 2 == 0 {
278///             continue;
279///         }
280///         if unit > 5 {
281///             continue 'tens;
282///         }
283///         println!("{}", ten * 10 + unit);
284///     }
285/// }
286/// ```
287///
288/// See [continue expressions] from the reference for more details.
289///
290/// [continue expressions]: ../reference/expressions/loop-expr.html#continue-expressions
291mod continue_keyword {}
292
293#[doc(keyword = "crate")]
294//
295/// A Rust binary or library.
296///
297/// The primary use of the `crate` keyword is as a part of `extern crate` declarations, which are
298/// used to specify a dependency on a crate external to the one it's declared in. Crates are the
299/// fundamental compilation unit of Rust code, and can be seen as libraries or projects. More can
300/// be read about crates in the [Reference].
301///
302/// ```rust ignore
303/// extern crate rand;
304/// extern crate my_crate as thing;
305/// extern crate std; // implicitly added to the root of every Rust project
306/// ```
307///
308/// The `as` keyword can be used to change what the crate is referred to as in your project. If a
309/// crate name includes a dash, it is implicitly imported with the dashes replaced by underscores.
310///
311/// `crate` can also be used as in conjunction with `pub` to signify that the item it's attached to
312/// is public only to other members of the same crate it's in.
313///
314/// ```rust
315/// # #[allow(unused_imports)]
316/// pub(crate) use std::io::Error as IoError;
317/// pub(crate) enum CoolMarkerType { }
318/// pub struct PublicThing {
319///     pub(crate) semi_secret_thing: bool,
320/// }
321/// ```
322///
323/// `crate` is also used to represent the absolute path of a module, where `crate` refers to the
324/// root of the current crate. For instance, `crate::foo::bar` refers to the name `bar` inside the
325/// module `foo`, from anywhere else in the same crate.
326///
327/// [Reference]: ../reference/items/extern-crates.html
328mod crate_keyword {}
329
330#[doc(keyword = "else")]
331//
332/// What expression to evaluate when an [`if`] condition evaluates to [`false`].
333///
334/// `else` expressions are optional. When no else expressions are supplied it is assumed to evaluate
335/// to the unit type `()`.
336///
337/// The type that the `else` blocks evaluate to must be compatible with the type that the `if` block
338/// evaluates to.
339///
340/// As can be seen below, `else` must be followed by either: `if`, `if let`, or a block `{}` and it
341/// will return the value of that expression.
342///
343/// ```rust
344/// let result = if true == false {
345///     "oh no"
346/// } else if "something" == "other thing" {
347///     "oh dear"
348/// } else if let Some(200) = "blarg".parse::<i32>().ok() {
349///     "uh oh"
350/// } else {
351///     println!("Sneaky side effect.");
352///     "phew, nothing's broken"
353/// };
354/// ```
355///
356/// Here's another example but here we do not try and return an expression:
357///
358/// ```rust
359/// if true == false {
360///     println!("oh no");
361/// } else if "something" == "other thing" {
362///     println!("oh dear");
363/// } else if let Some(200) = "blarg".parse::<i32>().ok() {
364///     println!("uh oh");
365/// } else {
366///     println!("phew, nothing's broken");
367/// }
368/// ```
369///
370/// The above is _still_ an expression but it will always evaluate to `()`.
371///
372/// There is possibly no limit to the number of `else` blocks that could follow an `if` expression
373/// however if you have several then a [`match`] expression might be preferable.
374///
375/// Read more about control flow in the [Rust Book].
376///
377/// [Rust Book]: ../book/ch03-05-control-flow.html#handling-multiple-conditions-with-else-if
378/// [`match`]: keyword.match.html
379/// [`false`]: keyword.false.html
380/// [`if`]: keyword.if.html
381mod else_keyword {}
382
383#[doc(keyword = "enum")]
384//
385/// A type that can be any one of several variants.
386///
387/// Enums in Rust are similar to those of other compiled languages like C, but have important
388/// differences that make them considerably more powerful. What Rust calls enums are more commonly
389/// known as [Algebraic Data Types][ADT] if you're coming from a functional programming background.
390/// The important detail is that each enum variant can have data to go along with it.
391///
392/// ```rust
393/// # struct Coord;
394/// enum SimpleEnum {
395///     FirstVariant,
396///     SecondVariant,
397///     ThirdVariant,
398/// }
399///
400/// enum Location {
401///     Unknown,
402///     Anonymous,
403///     Known(Coord),
404/// }
405///
406/// enum ComplexEnum {
407///     Nothing,
408///     Something(u32),
409///     LotsOfThings {
410///         usual_struct_stuff: bool,
411///         blah: String,
412///     }
413/// }
414///
415/// enum EmptyEnum { }
416/// ```
417///
418/// The first enum shown is the usual kind of enum you'd find in a C-style language. The second
419/// shows off a hypothetical example of something storing location data, with `Coord` being any
420/// other type that's needed, for example a struct. The third example demonstrates the kind of
421/// data a variant can store, ranging from nothing, to a tuple, to an anonymous struct.
422///
423/// Instantiating enum variants involves explicitly using the enum's name as its namespace,
424/// followed by one of its variants. `SimpleEnum::SecondVariant` would be an example from above.
425/// When data follows along with a variant, such as with rust's built-in [`Option`] type, the data
426/// is added as the type describes, for example `Option::Some(123)`. The same follows with
427/// struct-like variants, with things looking like `ComplexEnum::LotsOfThings { usual_struct_stuff:
428/// true, blah: "hello!".to_string(), }`. Empty Enums are similar to [`!`] in that they cannot be
429/// instantiated at all, and are used mainly to mess with the type system in interesting ways.
430///
431/// For more information, take a look at the [Rust Book] or the [Reference]
432///
433/// [ADT]: https://en.wikipedia.org/wiki/Algebraic_data_type
434/// [Rust Book]: ../book/ch06-01-defining-an-enum.html
435/// [Reference]: ../reference/items/enumerations.html
436mod enum_keyword {}
437
438#[doc(keyword = "extern")]
439//
440/// Link to or import external code.
441///
442/// The `extern` keyword is used in two places in Rust. One is in conjunction with the [`crate`]
443/// keyword to make your Rust code aware of other Rust crates in your project, i.e., `extern crate
444/// lazy_static;`. The other use is in foreign function interfaces (FFI).
445///
446/// `extern` is used in two different contexts within FFI. The first is in the form of external
447/// blocks, for declaring function interfaces that Rust code can call foreign code by. This use
448/// of `extern` is unsafe, since we are asserting to the compiler that all function declarations
449/// are correct. If they are not, using these items may lead to undefined behavior.
450///
451/// ```rust ignore
452/// // SAFETY: The function declarations given below are in
453/// // line with the header files of `my_c_library`.
454/// #[link(name = "my_c_library")]
455/// unsafe extern "C" {
456///     fn my_c_function(x: i32) -> bool;
457/// }
458/// ```
459///
460/// This code would attempt to link with `libmy_c_library.so` on unix-like systems and
461/// `my_c_library.dll` on Windows at runtime, and panic if it can't find something to link to. Rust
462/// code could then use `my_c_function` as if it were any other unsafe Rust function. Working with
463/// non-Rust languages and FFI is inherently unsafe, so wrappers are usually built around C APIs.
464///
465/// The mirror use case of FFI is also done via the `extern` keyword:
466///
467/// ```rust
468/// #[unsafe(no_mangle)]
469/// pub extern "C" fn callable_from_c(x: i32) -> bool {
470///     x % 3 == 0
471/// }
472/// ```
473///
474/// If compiled as a dylib, the resulting .so could then be linked to from a C library, and the
475/// function could be used as if it was from any other library.
476///
477/// For more information on FFI, check the [Rust book] or the [Reference].
478///
479/// [Rust book]:
480/// ../book/ch19-01-unsafe-rust.html#using-extern-functions-to-call-external-code
481/// [Reference]: ../reference/items/external-blocks.html
482/// [`crate`]: keyword.crate.html
483mod extern_keyword {}
484
485#[doc(keyword = "false")]
486//
487/// A value of type [`bool`] representing logical **false**.
488///
489/// `false` is the logical opposite of [`true`].
490///
491/// See the documentation for [`true`] for more information.
492///
493/// [`true`]: keyword.true.html
494mod false_keyword {}
495
496#[doc(keyword = "fn")]
497//
498/// A function or function pointer.
499///
500/// Functions are the primary way code is executed within Rust. Function blocks, usually just
501/// called functions, can be defined in a variety of different places and be assigned many
502/// different attributes and modifiers.
503///
504/// Standalone functions that just sit within a module not attached to anything else are common,
505/// but most functions will end up being inside [`impl`] blocks, either on another type itself, or
506/// as a trait impl for that type.
507///
508/// ```rust
509/// fn standalone_function() {
510///     // code
511/// }
512///
513/// pub fn public_thing(argument: bool) -> String {
514///     // code
515///     # "".to_string()
516/// }
517///
518/// struct Thing {
519///     foo: i32,
520/// }
521///
522/// impl Thing {
523///     pub fn new() -> Self {
524///         Self {
525///             foo: 42,
526///         }
527///     }
528/// }
529/// ```
530///
531/// In addition to presenting fixed types in the form of `fn name(arg: type, ..) -> return_type`,
532/// functions can also declare a list of type parameters along with trait bounds that they fall
533/// into.
534///
535/// ```rust
536/// fn generic_function<T: Clone>(x: T) -> (T, T, T) {
537///     (x.clone(), x.clone(), x.clone())
538/// }
539///
540/// fn generic_where<T>(x: T) -> T
541///     where T: std::ops::Add<Output = T> + Copy
542/// {
543///     x + x + x
544/// }
545/// ```
546///
547/// Declaring trait bounds in the angle brackets is functionally identical to using a `where`
548/// clause. It's up to the programmer to decide which works better in each situation, but `where`
549/// tends to be better when things get longer than one line.
550///
551/// Along with being made public via `pub`, `fn` can also have an [`extern`] added for use in
552/// FFI.
553///
554/// For more information on the various types of functions and how they're used, consult the [Rust
555/// book] or the [Reference].
556///
557/// [`impl`]: keyword.impl.html
558/// [`extern`]: keyword.extern.html
559/// [Rust book]: ../book/ch03-03-how-functions-work.html
560/// [Reference]: ../reference/items/functions.html
561mod fn_keyword {}
562
563#[doc(keyword = "for")]
564//
565/// Iteration with [`in`], trait implementation with [`impl`], or [higher-ranked trait bounds]
566/// (`for<'a>`).
567///
568/// The `for` keyword is used in many syntactic locations:
569///
570/// * `for` is used in for-in-loops (see below).
571/// * `for` is used when implementing traits as in `impl Trait for Type` (see [`impl`] for more info
572///   on that).
573/// * `for` is also used for [higher-ranked trait bounds] as in `for<'a> &'a T: PartialEq<i32>`.
574///
575/// for-in-loops, or to be more precise, iterator loops, are a simple syntactic sugar over a common
576/// practice within Rust, which is to loop over anything that implements [`IntoIterator`] until the
577/// iterator returned by `.into_iter()` returns `None` (or the loop body uses `break`).
578///
579/// ```rust
580/// for i in 0..5 {
581///     println!("{}", i * 2);
582/// }
583///
584/// for i in std::iter::repeat(5) {
585///     println!("turns out {i} never stops being 5");
586///     break; // would loop forever otherwise
587/// }
588///
589/// 'outer: for x in 5..50 {
590///     for y in 0..10 {
591///         if x == y {
592///             break 'outer;
593///         }
594///     }
595/// }
596/// ```
597///
598/// As shown in the example above, `for` loops (along with all other loops) can be tagged, using
599/// similar syntax to lifetimes (only visually similar, entirely distinct in practice). Giving the
600/// same tag to `break` breaks the tagged loop, which is useful for inner loops. It is definitely
601/// not a goto.
602///
603/// A `for` loop expands as shown:
604///
605/// ```rust
606/// # fn code() { }
607/// # let iterator = 0..2;
608/// for loop_variable in iterator {
609///     code()
610/// }
611/// ```
612///
613/// ```rust
614/// # fn code() { }
615/// # let iterator = 0..2;
616/// {
617///     let result = match IntoIterator::into_iter(iterator) {
618///         mut iter => loop {
619///             match iter.next() {
620///                 None => break,
621///                 Some(loop_variable) => { code(); },
622///             };
623///         },
624///     };
625///     result
626/// }
627/// ```
628///
629/// More details on the functionality shown can be seen at the [`IntoIterator`] docs.
630///
631/// For more information on for-loops, see the [Rust book] or the [Reference].
632///
633/// See also, [`loop`], [`while`].
634///
635/// [`in`]: keyword.in.html
636/// [`impl`]: keyword.impl.html
637/// [`loop`]: keyword.loop.html
638/// [`while`]: keyword.while.html
639/// [higher-ranked trait bounds]: ../reference/trait-bounds.html#higher-ranked-trait-bounds
640/// [Rust book]:
641/// ../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
642/// [Reference]: ../reference/expressions/loop-expr.html#iterator-loops
643mod for_keyword {}
644
645#[doc(keyword = "if")]
646//
647/// Evaluate a block if a condition holds.
648///
649/// `if` is a familiar construct to most programmers, and is the main way you'll often do logic in
650/// your code. However, unlike in most languages, `if` blocks can also act as expressions.
651///
652/// ```rust
653/// # let rude = true;
654/// if 1 == 2 {
655///     println!("whoops, mathematics broke");
656/// } else {
657///     println!("everything's fine!");
658/// }
659///
660/// let greeting = if rude {
661///     "sup nerd."
662/// } else {
663///     "hello, friend!"
664/// };
665///
666/// if let Ok(x) = "123".parse::<i32>() {
667///     println!("{} double that and you get {}!", greeting, x * 2);
668/// }
669/// ```
670///
671/// Shown above are the three typical forms an `if` block comes in. First is the usual kind of
672/// thing you'd see in many languages, with an optional `else` block. Second uses `if` as an
673/// expression, which is only possible if all branches return the same type. An `if` expression can
674/// be used everywhere you'd expect. The third kind of `if` block is an `if let` block, which
675/// behaves similarly to using a `match` expression:
676///
677/// ```rust
678/// if let Some(x) = Some(123) {
679///     // code
680///     # let _ = x;
681/// } else {
682///     // something else
683/// }
684///
685/// match Some(123) {
686///     Some(x) => {
687///         // code
688///         # let _ = x;
689///     },
690///     _ => {
691///         // something else
692///     },
693/// }
694/// ```
695///
696/// Each kind of `if` expression can be mixed and matched as needed.
697///
698/// ```rust
699/// if true == false {
700///     println!("oh no");
701/// } else if "something" == "other thing" {
702///     println!("oh dear");
703/// } else if let Some(200) = "blarg".parse::<i32>().ok() {
704///     println!("uh oh");
705/// } else {
706///     println!("phew, nothing's broken");
707/// }
708/// ```
709///
710/// The `if` keyword is used in one other place in Rust, namely as a part of pattern matching
711/// itself, allowing patterns such as `Some(x) if x > 200` to be used.
712///
713/// For more information on `if` expressions, see the [Rust book] or the [Reference].
714///
715/// [Rust book]: ../book/ch03-05-control-flow.html#if-expressions
716/// [Reference]: ../reference/expressions/if-expr.html
717mod if_keyword {}
718
719#[doc(keyword = "impl")]
720//
721/// Implementations of functionality for a type, or a type implementing some functionality.
722///
723/// There are two uses of the keyword `impl`:
724///  * An `impl` block is an item that is used to implement some functionality for a type.
725///  * An `impl Trait` in a type-position can be used to designate a type that implements a trait called `Trait`.
726///
727/// # Implementing Functionality for a Type
728///
729/// The `impl` keyword is primarily used to define implementations on types. Inherent
730/// implementations are standalone, while trait implementations are used to implement traits for
731/// types, or other traits.
732///
733/// An implementation consists of definitions of functions and consts. A function defined in an
734/// `impl` block can be standalone, meaning it would be called like `Vec::new()`. If the function
735/// takes `self`, `&self`, or `&mut self` as its first argument, it can also be called using
736/// method-call syntax, a familiar feature to any object-oriented programmer, like `vec.len()`.
737///
738/// ## Inherent Implementations
739///
740/// ```rust
741/// struct Example {
742///     number: i32,
743/// }
744///
745/// impl Example {
746///     fn boo() {
747///         println!("boo! Example::boo() was called!");
748///     }
749///
750///     fn answer(&mut self) {
751///         self.number += 42;
752///     }
753///
754///     fn get_number(&self) -> i32 {
755///         self.number
756///     }
757/// }
758/// ```
759///
760/// It matters little where an inherent implementation is defined;
761/// its functionality is in scope wherever its implementing type is.
762///
763/// ## Trait Implementations
764///
765/// ```rust
766/// struct Example {
767///     number: i32,
768/// }
769///
770/// trait Thingy {
771///     fn do_thingy(&self);
772/// }
773///
774/// impl Thingy for Example {
775///     fn do_thingy(&self) {
776///         println!("doing a thing! also, number is {}!", self.number);
777///     }
778/// }
779/// ```
780///
781/// It matters little where a trait implementation is defined;
782/// its functionality can be brought into scope by importing the trait it implements.
783///
784/// For more information on implementations, see the [Rust book][book1] or the [Reference].
785///
786/// # Designating a Type that Implements Some Functionality
787///
788/// The other use of the `impl` keyword is in `impl Trait` syntax, which can be understood to mean
789/// "any (or some) concrete type that implements Trait".
790/// It can be used as the type of a variable declaration,
791/// in [argument position](https://rust-lang.github.io/rfcs/1951-expand-impl-trait.html)
792/// or in [return position](https://rust-lang.github.io/rfcs/3425-return-position-impl-trait-in-traits.html).
793/// One pertinent use case is in working with closures, which have unnameable types.
794///
795/// ```rust
796/// fn thing_returning_closure() -> impl Fn(i32) -> bool {
797///     println!("here's a closure for you!");
798///     |x: i32| x % 3 == 0
799/// }
800/// ```
801///
802/// For more information on `impl Trait` syntax, see the [Rust book][book2].
803///
804/// [book1]: ../book/ch05-03-method-syntax.html
805/// [Reference]: ../reference/items/implementations.html
806/// [book2]: ../book/ch10-02-traits.html#returning-types-that-implement-traits
807mod impl_keyword {}
808
809#[doc(keyword = "in")]
810//
811/// Iterate over a series of values with [`for`].
812///
813/// The expression immediately following `in` must implement the [`IntoIterator`] trait.
814///
815/// ## Literal Examples:
816///
817///    * `for _ in 1..3 {}` - Iterate over an exclusive range up to but excluding 3.
818///    * `for _ in 1..=3 {}` - Iterate over an inclusive range up to and including 3.
819///
820/// (Read more about [range patterns])
821///
822/// [`IntoIterator`]: ../book/ch13-04-performance.html
823/// [range patterns]: ../reference/patterns.html?highlight=range#range-patterns
824/// [`for`]: keyword.for.html
825///
826/// The other use of `in` is with the keyword `pub`. It allows users to declare an item as visible
827/// only within a given scope.
828///
829/// ## Literal Example:
830///
831///    * `pub(in crate::outer_mod) fn outer_mod_visible_fn() {}` - fn is visible in `outer_mod`
832///
833/// Starting with the 2018 edition, paths for `pub(in path)` must start with `crate`, `self` or
834/// `super`. The 2015 edition may also use paths starting with `::` or modules from the crate root.
835///
836/// For more information, see the [Reference].
837///
838/// [Reference]: ../reference/visibility-and-privacy.html#pubin-path-pubcrate-pubsuper-and-pubself
839mod in_keyword {}
840
841#[doc(keyword = "let")]
842//
843/// Bind a value to a variable.
844///
845/// The primary use for the `let` keyword is in `let` statements, which are used to introduce a new
846/// set of variables into the current scope, as given by a pattern.
847///
848/// ```rust
849/// # #![allow(unused_assignments)]
850/// let thing1: i32 = 100;
851/// let thing2 = 200 + thing1;
852///
853/// let mut changing_thing = true;
854/// changing_thing = false;
855///
856/// let (part1, part2) = ("first", "second");
857///
858/// struct Example {
859///     a: bool,
860///     b: u64,
861/// }
862///
863/// let Example { a, b: _ } = Example {
864///     a: true,
865///     b: 10004,
866/// };
867/// assert!(a);
868/// ```
869///
870/// The pattern is most commonly a single variable, which means no pattern matching is done and
871/// the expression given is bound to the variable. Apart from that, patterns used in `let` bindings
872/// can be as complicated as needed, given that the pattern is exhaustive. See the [Rust
873/// book][book1] for more information on pattern matching. The type of the pattern is optionally
874/// given afterwards, but if left blank is automatically inferred by the compiler if possible.
875///
876/// Variables in Rust are immutable by default, and require the `mut` keyword to be made mutable.
877///
878/// Multiple variables can be defined with the same name, known as shadowing. This doesn't affect
879/// the original variable in any way beyond being unable to directly access it beyond the point of
880/// shadowing. It continues to remain in scope, getting dropped only when it falls out of scope.
881/// Shadowed variables don't need to have the same type as the variables shadowing them.
882///
883/// ```rust
884/// let shadowing_example = true;
885/// let shadowing_example = 123.4;
886/// let shadowing_example = shadowing_example as u32;
887/// let mut shadowing_example = format!("cool! {shadowing_example}");
888/// shadowing_example += " something else!"; // not shadowing
889/// ```
890///
891/// Other places the `let` keyword is used include along with [`if`], in the form of `if let`
892/// expressions. They're useful if the pattern being matched isn't exhaustive, such as with
893/// enumerations. `while let` also exists, which runs a loop with a pattern matched value until
894/// that pattern can't be matched.
895///
896/// For more information on the `let` keyword, see the [Rust book][book2] or the [Reference]
897///
898/// [book1]: ../book/ch06-02-match.html
899/// [`if`]: keyword.if.html
900/// [book2]: ../book/ch18-01-all-the-places-for-patterns.html#let-statements
901/// [Reference]: ../reference/statements.html#let-statements
902mod let_keyword {}
903
904#[doc(keyword = "loop")]
905//
906/// Loop indefinitely.
907///
908/// `loop` is used to define the simplest kind of loop supported in Rust. It runs the code inside
909/// it until the code uses `break` or the program exits.
910///
911/// ```rust
912/// loop {
913///     println!("hello world forever!");
914///     # break;
915/// }
916///
917/// let mut i = 1;
918/// loop {
919///     println!("i is {i}");
920///     if i > 100 {
921///         break;
922///     }
923///     i *= 2;
924/// }
925/// assert_eq!(i, 128);
926/// ```
927///
928/// Unlike the other kinds of loops in Rust (`while`, `while let`, and `for`), loops can be used as
929/// expressions that return values via `break`.
930///
931/// ```rust
932/// let mut i = 1;
933/// let something = loop {
934///     i *= 2;
935///     if i > 100 {
936///         break i;
937///     }
938/// };
939/// assert_eq!(something, 128);
940/// ```
941///
942/// Every `break` in a loop has to have the same type. When it's not explicitly giving something,
943/// `break;` returns `()`.
944///
945/// For more information on `loop` and loops in general, see the [Reference].
946///
947/// See also, [`for`], [`while`].
948///
949/// [`for`]: keyword.for.html
950/// [`while`]: keyword.while.html
951/// [Reference]: ../reference/expressions/loop-expr.html
952mod loop_keyword {}
953
954#[doc(keyword = "match")]
955//
956/// Control flow based on pattern matching.
957///
958/// `match` can be used to run code conditionally. Every pattern must
959/// be handled exhaustively either explicitly or by using wildcards like
960/// `_` in the `match`. Since `match` is an expression, values can also be
961/// returned.
962///
963/// ```rust
964/// let opt = Option::None::<usize>;
965/// let x = match opt {
966///     Some(int) => int,
967///     None => 10,
968/// };
969/// assert_eq!(x, 10);
970///
971/// let a_number = Option::Some(10);
972/// match a_number {
973///     Some(x) if x <= 5 => println!("0 to 5 num = {x}"),
974///     Some(x @ 6..=10) => println!("6 to 10 num = {x}"),
975///     None => panic!(),
976///     // all other numbers
977///     _ => panic!(),
978/// }
979/// ```
980///
981/// `match` can be used to gain access to the inner members of an enum
982/// and use them directly.
983///
984/// ```rust
985/// enum Outer {
986///     Double(Option<u8>, Option<String>),
987///     Single(Option<u8>),
988///     Empty
989/// }
990///
991/// let get_inner = Outer::Double(None, Some(String::new()));
992/// match get_inner {
993///     Outer::Double(None, Some(st)) => println!("{st}"),
994///     Outer::Single(opt) => println!("{opt:?}"),
995///     _ => panic!(),
996/// }
997/// ```
998///
999/// For more information on `match` and matching in general, see the [Reference].
1000///
1001/// [Reference]: ../reference/expressions/match-expr.html
1002mod match_keyword {}
1003
1004#[doc(keyword = "mod")]
1005//
1006/// Organize code into [modules].
1007///
1008/// Use `mod` to create new [modules] to encapsulate code, including other
1009/// modules:
1010///
1011/// ```
1012/// mod foo {
1013///     mod bar {
1014///         type MyType = (u8, u8);
1015///         fn baz() {}
1016///     }
1017/// }
1018/// ```
1019///
1020/// Like [`struct`]s and [`enum`]s, a module and its content are private by
1021/// default, inaccessible to code outside of the module.
1022///
1023/// To learn more about allowing access, see the documentation for the [`pub`]
1024/// keyword.
1025///
1026/// [`enum`]: keyword.enum.html
1027/// [`pub`]: keyword.pub.html
1028/// [`struct`]: keyword.struct.html
1029/// [modules]: ../reference/items/modules.html
1030mod mod_keyword {}
1031
1032#[doc(keyword = "move")]
1033//
1034/// Capture a [closure]'s environment by value.
1035///
1036/// `move` converts any variables captured by reference or mutable reference
1037/// to variables captured by value.
1038///
1039/// ```rust
1040/// let data = vec![1, 2, 3];
1041/// let closure = move || println!("captured {data:?} by value");
1042///
1043/// // data is no longer available, it is owned by the closure
1044/// ```
1045///
1046/// Note: `move` closures may still implement [`Fn`] or [`FnMut`], even though
1047/// they capture variables by `move`. This is because the traits implemented by
1048/// a closure type are determined by *what* the closure does with captured
1049/// values, not *how* it captures them:
1050///
1051/// ```rust
1052/// fn create_fn() -> impl Fn() {
1053///     let text = "Fn".to_owned();
1054///     move || println!("This is a: {text}")
1055/// }
1056///
1057/// let fn_plain = create_fn();
1058/// fn_plain();
1059/// ```
1060///
1061/// `move` is often used when [threads] are involved.
1062///
1063/// ```rust
1064/// let data = vec![1, 2, 3];
1065///
1066/// std::thread::spawn(move || {
1067///     println!("captured {data:?} by value")
1068/// }).join().unwrap();
1069///
1070/// // data was moved to the spawned thread, so we cannot use it here
1071/// ```
1072///
1073/// `move` is also valid before an async block.
1074///
1075/// ```rust
1076/// let capture = "hello".to_owned();
1077/// let block = async move {
1078///     println!("rust says {capture} from async block");
1079/// };
1080/// ```
1081///
1082/// For more information on the `move` keyword, see the [closures][closure] section
1083/// of the Rust book or the [threads] section.
1084///
1085/// [closure]: ../book/ch13-01-closures.html
1086/// [threads]: ../book/ch16-01-threads.html#using-move-closures-with-threads
1087mod move_keyword {}
1088
1089#[doc(keyword = "mut")]
1090//
1091/// A mutable variable, reference, or pointer.
1092///
1093/// `mut` can be used in several situations. The first is mutable variables,
1094/// which can be used anywhere you can bind a value to a variable name. Some
1095/// examples:
1096///
1097/// ```rust
1098/// // A mutable variable in the parameter list of a function.
1099/// fn foo(mut x: u8, y: u8) -> u8 {
1100///     x += y;
1101///     x
1102/// }
1103///
1104/// // Modifying a mutable variable.
1105/// # #[allow(unused_assignments)]
1106/// let mut a = 5;
1107/// a = 6;
1108///
1109/// assert_eq!(foo(3, 4), 7);
1110/// assert_eq!(a, 6);
1111/// ```
1112///
1113/// The second is mutable references. They can be created from `mut` variables
1114/// and must be unique: no other variables can have a mutable reference, nor a
1115/// shared reference.
1116///
1117/// ```rust
1118/// // Taking a mutable reference.
1119/// fn push_two(v: &mut Vec<u8>) {
1120///     v.push(2);
1121/// }
1122///
1123/// // A mutable reference cannot be taken to a non-mutable variable.
1124/// let mut v = vec![0, 1];
1125/// // Passing a mutable reference.
1126/// push_two(&mut v);
1127///
1128/// assert_eq!(v, vec![0, 1, 2]);
1129/// ```
1130///
1131/// ```rust,compile_fail,E0502
1132/// let mut v = vec![0, 1];
1133/// let mut_ref_v = &mut v;
1134/// # #[allow(unused)]
1135/// let ref_v = &v;
1136/// mut_ref_v.push(2);
1137/// ```
1138///
1139/// Mutable raw pointers work much like mutable references, with the added
1140/// possibility of not pointing to a valid object. The syntax is `*mut Type`.
1141///
1142/// More information on mutable references and pointers can be found in the [Reference].
1143///
1144/// [Reference]: ../reference/types/pointer.html#mutable-references-mut
1145mod mut_keyword {}
1146
1147#[doc(keyword = "pub")]
1148//
1149/// Make an item visible to others.
1150///
1151/// The keyword `pub` makes any module, function, or data structure accessible from inside
1152/// of external modules. The `pub` keyword may also be used in a `use` declaration to re-export
1153/// an identifier from a namespace.
1154///
1155/// For more information on the `pub` keyword, please see the visibility section
1156/// of the [reference] and for some examples, see [Rust by Example].
1157///
1158/// [reference]:../reference/visibility-and-privacy.html?highlight=pub#visibility-and-privacy
1159/// [Rust by Example]:../rust-by-example/mod/visibility.html
1160mod pub_keyword {}
1161
1162#[doc(keyword = "ref")]
1163//
1164/// Bind by reference during pattern matching.
1165///
1166/// `ref` annotates pattern bindings to make them borrow rather than move.
1167/// It is **not** a part of the pattern as far as matching is concerned: it does
1168/// not affect *whether* a value is matched, only *how* it is matched.
1169///
1170/// By default, [`match`] statements consume all they can, which can sometimes
1171/// be a problem, when you don't really need the value to be moved and owned:
1172///
1173/// ```compile_fail,E0382
1174/// let maybe_name = Some(String::from("Alice"));
1175/// // The variable 'maybe_name' is consumed here ...
1176/// match maybe_name {
1177///     Some(n) => println!("Hello, {n}"),
1178///     _ => println!("Hello, world"),
1179/// }
1180/// // ... and is now unavailable.
1181/// println!("Hello again, {}", maybe_name.unwrap_or("world".into()));
1182/// ```
1183///
1184/// Using the `ref` keyword, the value is only borrowed, not moved, making it
1185/// available for use after the [`match`] statement:
1186///
1187/// ```
1188/// let maybe_name = Some(String::from("Alice"));
1189/// // Using `ref`, the value is borrowed, not moved ...
1190/// match maybe_name {
1191///     Some(ref n) => println!("Hello, {n}"),
1192///     _ => println!("Hello, world"),
1193/// }
1194/// // ... so it's available here!
1195/// println!("Hello again, {}", maybe_name.unwrap_or("world".into()));
1196/// ```
1197///
1198/// # `&` vs `ref`
1199///
1200/// - `&` denotes that your pattern expects a reference to an object. Hence `&`
1201/// is a part of said pattern: `&Foo` matches different objects than `Foo` does.
1202///
1203/// - `ref` indicates that you want a reference to an unpacked value. It is not
1204/// matched against: `Foo(ref foo)` matches the same objects as `Foo(foo)`.
1205///
1206/// See also the [Reference] for more information.
1207///
1208/// [`match`]: keyword.match.html
1209/// [Reference]: ../reference/patterns.html#identifier-patterns
1210mod ref_keyword {}
1211
1212#[doc(keyword = "return")]
1213//
1214/// Returns a value from a function.
1215///
1216/// A `return` marks the end of an execution path in a function:
1217///
1218/// ```
1219/// fn foo() -> i32 {
1220///     return 3;
1221/// }
1222/// assert_eq!(foo(), 3);
1223/// ```
1224///
1225/// `return` is not needed when the returned value is the last expression in the
1226/// function. In this case the `;` is omitted:
1227///
1228/// ```
1229/// fn foo() -> i32 {
1230///     3
1231/// }
1232/// assert_eq!(foo(), 3);
1233/// ```
1234///
1235/// `return` returns from the function immediately (an "early return"):
1236///
1237/// ```no_run
1238/// use std::fs::File;
1239/// use std::io::{Error, ErrorKind, Read, Result};
1240///
1241/// fn main() -> Result<()> {
1242///     let mut file = match File::open("foo.txt") {
1243///         Ok(f) => f,
1244///         Err(e) => return Err(e),
1245///     };
1246///
1247///     let mut contents = String::new();
1248///     let size = match file.read_to_string(&mut contents) {
1249///         Ok(s) => s,
1250///         Err(e) => return Err(e),
1251///     };
1252///
1253///     if contents.contains("impossible!") {
1254///         return Err(Error::new(ErrorKind::Other, "oh no!"));
1255///     }
1256///
1257///     if size > 9000 {
1258///         return Err(Error::new(ErrorKind::Other, "over 9000!"));
1259///     }
1260///
1261///     assert_eq!(contents, "Hello, world!");
1262///     Ok(())
1263/// }
1264/// ```
1265///
1266/// Within [closures] and [`async`] blocks, `return` returns a value from within the closure or
1267/// `async` block, not from the parent function:
1268///
1269/// ```rust
1270/// fn foo() -> i32 {
1271///     let closure = || {
1272///         return 5;
1273///     };
1274///
1275///     let future = async {
1276///         return 10;
1277///     };
1278///
1279///     return 15;
1280/// }
1281///
1282/// assert_eq!(foo(), 15);
1283/// ```
1284///
1285/// [closures]: ../book/ch13-01-closures.html
1286/// [`async`]: ../std/keyword.async.html
1287mod return_keyword {}
1288
1289#[doc(keyword = "become")]
1290//
1291/// Perform a tail-call of a function.
1292///
1293/// <div class="warning">
1294///
1295/// `feature(explicit_tail_calls)` is currently incomplete and may not work properly.
1296/// </div>
1297///
1298/// When tail calling a function, instead of its stack frame being added to the
1299/// stack, the stack frame of the caller is directly replaced with the callee's.
1300/// This means that as long as a loop in a call graph only uses tail calls, the
1301/// stack growth will be bounded.
1302///
1303/// This is useful for writing functional-style code (since it prevents recursion
1304/// from exhausting resources) or for code optimization (since a tail call
1305/// *might* be cheaper than a normal call, tail calls can be used in a similar
1306/// manner to computed goto).
1307///
1308/// Example of using `become` to implement functional-style `fold`:
1309/// ```
1310/// #![feature(explicit_tail_calls)]
1311/// #![expect(incomplete_features)]
1312///
1313/// fn fold<T: Copy, S>(slice: &[T], init: S, f: impl Fn(S, T) -> S) -> S {
1314///     match slice {
1315///         // without `become`, on big inputs this could easily overflow the
1316///         // stack. using a tail call guarantees that the stack will not grow unboundedly
1317///         [first, rest @ ..] => become fold(rest, f(init, *first), f),
1318///         [] => init,
1319///     }
1320/// }
1321/// ```
1322///
1323/// Compilers can already perform "tail call optimization" -- they can replace normal
1324/// calls with tail calls, although there are no guarantees that this will be done.
1325/// However, to perform TCO, the call needs to be the last thing that happens
1326/// in the functions and be returned from it. This requirement is often broken
1327/// by drop code for locals, which is run after computing the return expression:
1328///
1329/// ```
1330/// fn example() {
1331///     let string = "meow".to_owned();
1332///     println!("{string}");
1333///     return help(); // this is *not* the last thing that happens in `example`...
1334/// }
1335///
1336/// // ... because it is desugared to this:
1337/// fn example_desugared() {
1338///     let string = "meow".to_owned();
1339///     println!("{string}");
1340///     let tmp = help();
1341///     drop(string);
1342///     return tmp;
1343/// }
1344///
1345/// fn help() {}
1346/// ```
1347///
1348/// For this reason, `become` also changes the drop order, such that locals are
1349/// dropped *before* evaluating the call.
1350///
1351/// In order to guarantee that the compiler can perform a tail call, `become`
1352/// currently has these requirements:
1353/// 1. callee and caller must have the same ABI, arguments, and return type
1354/// 2. callee and caller must not have varargs
1355/// 3. caller must not be marked with `#[track_caller]`
1356///    - callee is allowed to be marked with `#[track_caller]` as otherwise
1357///      adding `#[track_caller]` would be a breaking change. if callee is
1358///      marked with `#[track_caller]` a tail call is not guaranteed.
1359/// 4. callee and caller cannot be a closure
1360///    (unless it's coerced to a function pointer)
1361///
1362/// It is possible to tail-call a function pointer:
1363/// ```
1364/// #![feature(explicit_tail_calls)]
1365/// #![expect(incomplete_features)]
1366///
1367/// #[derive(Copy, Clone)]
1368/// enum Inst { Inc, Dec }
1369///
1370/// fn dispatch(stream: &[Inst], state: u32) -> u32 {
1371///     const TABLE: &[fn(&[Inst], u32) -> u32] = &[increment, decrement];
1372///     match stream {
1373///         [inst, rest @ ..] => become TABLE[*inst as usize](rest, state),
1374///         [] => state,
1375///     }
1376/// }
1377///
1378/// fn increment(stream: &[Inst], state: u32) -> u32 {
1379///     become dispatch(stream, state + 1)
1380/// }
1381///
1382/// fn decrement(stream: &[Inst], state: u32) -> u32 {
1383///     become dispatch(stream, state - 1)
1384/// }
1385///
1386/// let program = &[Inst::Inc, Inst::Inc, Inst::Dec, Inst::Inc];
1387/// assert_eq!(dispatch(program, 0), 2);
1388/// ```
1389mod become_keyword {}
1390
1391#[doc(keyword = "self")]
1392//
1393/// The receiver of a method, or the current module.
1394///
1395/// `self` is used in two situations: referencing the current module and marking
1396/// the receiver of a method.
1397///
1398/// In paths, `self` can be used to refer to the current module, either in a
1399/// [`use`] statement or in a path to access an element:
1400///
1401/// ```
1402/// # #![allow(unused_imports)]
1403/// use std::io::{self, Read};
1404/// ```
1405///
1406/// Is functionally the same as:
1407///
1408/// ```
1409/// # #![allow(unused_imports)]
1410/// use std::io;
1411/// use std::io::Read;
1412/// ```
1413///
1414/// Using `self` to access an element in the current module:
1415///
1416/// ```
1417/// # #![allow(dead_code)]
1418/// # fn main() {}
1419/// fn foo() {}
1420/// fn bar() {
1421///     self::foo()
1422/// }
1423/// ```
1424///
1425/// `self` as the current receiver for a method allows to omit the parameter
1426/// type most of the time. With the exception of this particularity, `self` is
1427/// used much like any other parameter:
1428///
1429/// ```
1430/// struct Foo(i32);
1431///
1432/// impl Foo {
1433///     // No `self`.
1434///     fn new() -> Self {
1435///         Self(0)
1436///     }
1437///
1438///     // Consuming `self`.
1439///     fn consume(self) -> Self {
1440///         Self(self.0 + 1)
1441///     }
1442///
1443///     // Borrowing `self`.
1444///     fn borrow(&self) -> &i32 {
1445///         &self.0
1446///     }
1447///
1448///     // Borrowing `self` mutably.
1449///     fn borrow_mut(&mut self) -> &mut i32 {
1450///         &mut self.0
1451///     }
1452/// }
1453///
1454/// // This method must be called with a `Type::` prefix.
1455/// let foo = Foo::new();
1456/// assert_eq!(foo.0, 0);
1457///
1458/// // Those two calls produces the same result.
1459/// let foo = Foo::consume(foo);
1460/// assert_eq!(foo.0, 1);
1461/// let foo = foo.consume();
1462/// assert_eq!(foo.0, 2);
1463///
1464/// // Borrowing is handled automatically with the second syntax.
1465/// let borrow_1 = Foo::borrow(&foo);
1466/// let borrow_2 = foo.borrow();
1467/// assert_eq!(borrow_1, borrow_2);
1468///
1469/// // Borrowing mutably is handled automatically too with the second syntax.
1470/// let mut foo = Foo::new();
1471/// *Foo::borrow_mut(&mut foo) += 1;
1472/// assert_eq!(foo.0, 1);
1473/// *foo.borrow_mut() += 1;
1474/// assert_eq!(foo.0, 2);
1475/// ```
1476///
1477/// Note that this automatic conversion when calling `foo.method()` is not
1478/// limited to the examples above. See the [Reference] for more information.
1479///
1480/// [`use`]: keyword.use.html
1481/// [Reference]: ../reference/items/associated-items.html#methods
1482mod self_keyword {}
1483
1484// FIXME: Once rustdoc can handle URL conflicts on case insensitive file systems, we can replace
1485// these two lines with `#[doc(keyword = "Self")]` and update `is_doc_keyword` in
1486// `CheckAttrVisitor`.
1487#[doc(alias = "Self")]
1488#[doc(keyword = "SelfTy")]
1489//
1490/// The implementing type within a [`trait`] or [`impl`] block, or the current type within a type
1491/// definition.
1492///
1493/// Within a type definition:
1494///
1495/// ```
1496/// # #![allow(dead_code)]
1497/// struct Node {
1498///     elem: i32,
1499///     // `Self` is a `Node` here.
1500///     next: Option<Box<Self>>,
1501/// }
1502/// ```
1503///
1504/// In an [`impl`] block:
1505///
1506/// ```
1507/// struct Foo(i32);
1508///
1509/// impl Foo {
1510///     fn new() -> Self {
1511///         Self(0)
1512///     }
1513/// }
1514///
1515/// assert_eq!(Foo::new().0, Foo(0).0);
1516/// ```
1517///
1518/// Generic parameters are implicit with `Self`:
1519///
1520/// ```
1521/// # #![allow(dead_code)]
1522/// struct Wrap<T> {
1523///     elem: T,
1524/// }
1525///
1526/// impl<T> Wrap<T> {
1527///     fn new(elem: T) -> Self {
1528///         Self { elem }
1529///     }
1530/// }
1531/// ```
1532///
1533/// In a [`trait`] definition and related [`impl`] block:
1534///
1535/// ```
1536/// trait Example {
1537///     fn example() -> Self;
1538/// }
1539///
1540/// struct Foo(i32);
1541///
1542/// impl Example for Foo {
1543///     fn example() -> Self {
1544///         Self(42)
1545///     }
1546/// }
1547///
1548/// assert_eq!(Foo::example().0, Foo(42).0);
1549/// ```
1550///
1551/// [`impl`]: keyword.impl.html
1552/// [`trait`]: keyword.trait.html
1553mod self_upper_keyword {}
1554
1555#[doc(keyword = "static")]
1556//
1557/// A static item is a value which is valid for the entire duration of your
1558/// program (a `'static` lifetime).
1559///
1560/// On the surface, `static` items seem very similar to [`const`]s: both contain
1561/// a value, both require type annotations and both can only be initialized with
1562/// constant functions and values. However, `static`s are notably different in
1563/// that they represent a location in memory. That means that you can have
1564/// references to `static` items and potentially even modify them, making them
1565/// essentially global variables.
1566///
1567/// Static items do not call [`drop`] at the end of the program.
1568///
1569/// There are two types of `static` items: those declared in association with
1570/// the [`mut`] keyword and those without.
1571///
1572/// Static items cannot be moved:
1573///
1574/// ```rust,compile_fail,E0507
1575/// static VEC: Vec<u32> = vec![];
1576///
1577/// fn move_vec(v: Vec<u32>) -> Vec<u32> {
1578///     v
1579/// }
1580///
1581/// // This line causes an error
1582/// move_vec(VEC);
1583/// ```
1584///
1585/// # Simple `static`s
1586///
1587/// Accessing non-[`mut`] `static` items is considered safe, but some
1588/// restrictions apply. Most notably, the type of a `static` value needs to
1589/// implement the [`Sync`] trait, ruling out interior mutability containers
1590/// like [`RefCell`]. See the [Reference] for more information.
1591///
1592/// ```rust
1593/// static FOO: [i32; 5] = [1, 2, 3, 4, 5];
1594///
1595/// let r1 = &FOO as *const _;
1596/// let r2 = &FOO as *const _;
1597/// // With a strictly read-only static, references will have the same address
1598/// assert_eq!(r1, r2);
1599/// // A static item can be used just like a variable in many cases
1600/// println!("{FOO:?}");
1601/// ```
1602///
1603/// # Mutable `static`s
1604///
1605/// If a `static` item is declared with the [`mut`] keyword, then it is allowed
1606/// to be modified by the program. However, accessing mutable `static`s can
1607/// cause undefined behavior in a number of ways, for example due to data races
1608/// in a multithreaded context. As such, all accesses to mutable `static`s
1609/// require an [`unsafe`] block.
1610///
1611/// When possible, it's often better to use a non-mutable `static` with an
1612/// interior mutable type such as [`Mutex`], [`OnceLock`], or an [atomic].
1613///
1614/// Despite their unsafety, mutable `static`s are necessary in many contexts:
1615/// they can be used to represent global state shared by the whole program or in
1616/// [`extern`] blocks to bind to variables from C libraries.
1617///
1618/// In an [`extern`] block:
1619///
1620/// ```rust,no_run
1621/// # #![allow(dead_code)]
1622/// unsafe extern "C" {
1623///     static mut ERROR_MESSAGE: *mut std::os::raw::c_char;
1624/// }
1625/// ```
1626///
1627/// Mutable `static`s, just like simple `static`s, have some restrictions that
1628/// apply to them. See the [Reference] for more information.
1629///
1630/// [`const`]: keyword.const.html
1631/// [`extern`]: keyword.extern.html
1632/// [`mut`]: keyword.mut.html
1633/// [`unsafe`]: keyword.unsafe.html
1634/// [`Mutex`]: sync::Mutex
1635/// [`OnceLock`]: sync::OnceLock
1636/// [`RefCell`]: cell::RefCell
1637/// [atomic]: sync::atomic
1638/// [Reference]: ../reference/items/static-items.html
1639mod static_keyword {}
1640
1641#[doc(keyword = "struct")]
1642//
1643/// A type that is composed of other types.
1644///
1645/// Structs in Rust come in three flavors: Structs with named fields, tuple structs, and unit
1646/// structs.
1647///
1648/// ```rust
1649/// struct Regular {
1650///     field1: f32,
1651///     field2: String,
1652///     pub field3: bool
1653/// }
1654///
1655/// struct Tuple(u32, String);
1656///
1657/// struct Unit;
1658/// ```
1659///
1660/// Regular structs are the most commonly used. Each field defined within them has a name and a
1661/// type, and once defined can be accessed using `example_struct.field` syntax. The fields of a
1662/// struct share its mutability, so `foo.bar = 2;` would only be valid if `foo` was mutable. Adding
1663/// `pub` to a field makes it visible to code in other modules, as well as allowing it to be
1664/// directly accessed and modified.
1665///
1666/// Tuple structs are similar to regular structs, but its fields have no names. They are used like
1667/// tuples, with deconstruction possible via `let TupleStruct(x, y) = foo;` syntax. For accessing
1668/// individual variables, the same syntax is used as with regular tuples, namely `foo.0`, `foo.1`,
1669/// etc, starting at zero.
1670///
1671/// Unit structs are most commonly used as marker. They have a size of zero bytes, but unlike empty
1672/// enums they can be instantiated, making them isomorphic to the unit type `()`. Unit structs are
1673/// useful when you need to implement a trait on something, but don't need to store any data inside
1674/// it.
1675///
1676/// # Instantiation
1677///
1678/// Structs can be instantiated in different ways, all of which can be mixed and
1679/// matched as needed. The most common way to make a new struct is via a constructor method such as
1680/// `new()`, but when that isn't available (or you're writing the constructor itself), struct
1681/// literal syntax is used:
1682///
1683/// ```rust
1684/// # struct Foo { field1: f32, field2: String, etc: bool }
1685/// let example = Foo {
1686///     field1: 42.0,
1687///     field2: "blah".to_string(),
1688///     etc: true,
1689/// };
1690/// ```
1691///
1692/// It's only possible to directly instantiate a struct using struct literal syntax when all of its
1693/// fields are visible to you.
1694///
1695/// There are a handful of shortcuts provided to make writing constructors more convenient, most
1696/// common of which is the Field Init shorthand. When there is a variable and a field of the same
1697/// name, the assignment can be simplified from `field: field` into simply `field`. The following
1698/// example of a hypothetical constructor demonstrates this:
1699///
1700/// ```rust
1701/// struct User {
1702///     name: String,
1703///     admin: bool,
1704/// }
1705///
1706/// impl User {
1707///     pub fn new(name: String) -> Self {
1708///         Self {
1709///             name,
1710///             admin: false,
1711///         }
1712///     }
1713/// }
1714/// ```
1715///
1716/// Another shortcut for struct instantiation is available, used when you need to make a new
1717/// struct that has the same values as most of a previous struct of the same type, called struct
1718/// update syntax:
1719///
1720/// ```rust
1721/// # struct Foo { field1: String, field2: () }
1722/// # let thing = Foo { field1: "".to_string(), field2: () };
1723/// let updated_thing = Foo {
1724///     field1: "a new value".to_string(),
1725///     ..thing
1726/// };
1727/// ```
1728///
1729/// Tuple structs are instantiated in the same way as tuples themselves, except with the struct's
1730/// name as a prefix: `Foo(123, false, 0.1)`.
1731///
1732/// Empty structs are instantiated with just their name, and don't need anything else. `let thing =
1733/// EmptyStruct;`
1734///
1735/// # Style conventions
1736///
1737/// Structs are always written in UpperCamelCase, with few exceptions. While the trailing comma on a
1738/// struct's list of fields can be omitted, it's usually kept for convenience in adding and
1739/// removing fields down the line.
1740///
1741/// For more information on structs, take a look at the [Rust Book][book] or the
1742/// [Reference][reference].
1743///
1744/// [`PhantomData`]: marker::PhantomData
1745/// [book]: ../book/ch05-01-defining-structs.html
1746/// [reference]: ../reference/items/structs.html
1747mod struct_keyword {}
1748
1749#[doc(keyword = "super")]
1750//
1751/// The parent of the current [module].
1752///
1753/// ```rust
1754/// # #![allow(dead_code)]
1755/// # fn main() {}
1756/// mod a {
1757///     pub fn foo() {}
1758/// }
1759/// mod b {
1760///     pub fn foo() {
1761///         super::a::foo(); // call a's foo function
1762///     }
1763/// }
1764/// ```
1765///
1766/// It is also possible to use `super` multiple times: `super::super::foo`,
1767/// going up the ancestor chain.
1768///
1769/// See the [Reference] for more information.
1770///
1771/// [module]: ../reference/items/modules.html
1772/// [Reference]: ../reference/paths.html#super
1773mod super_keyword {}
1774
1775#[doc(keyword = "trait")]
1776//
1777/// A common interface for a group of types.
1778///
1779/// A `trait` is like an interface that data types can implement. When a type
1780/// implements a trait it can be treated abstractly as that trait using generics
1781/// or trait objects.
1782///
1783/// Traits can be made up of three varieties of associated items:
1784///
1785/// - functions and methods
1786/// - types
1787/// - constants
1788///
1789/// Traits may also contain additional type parameters. Those type parameters
1790/// or the trait itself can be constrained by other traits.
1791///
1792/// Traits can serve as markers or carry other logical semantics that
1793/// aren't expressed through their items. When a type implements that
1794/// trait it is promising to uphold its contract. [`Send`] and [`Sync`] are two
1795/// such marker traits present in the standard library.
1796///
1797/// See the [Reference][Ref-Traits] for a lot more information on traits.
1798///
1799/// # Examples
1800///
1801/// Traits are declared using the `trait` keyword. Types can implement them
1802/// using [`impl`] `Trait` [`for`] `Type`:
1803///
1804/// ```rust
1805/// trait Zero {
1806///     const ZERO: Self;
1807///     fn is_zero(&self) -> bool;
1808/// }
1809///
1810/// impl Zero for i32 {
1811///     const ZERO: Self = 0;
1812///
1813///     fn is_zero(&self) -> bool {
1814///         *self == Self::ZERO
1815///     }
1816/// }
1817///
1818/// assert_eq!(i32::ZERO, 0);
1819/// assert!(i32::ZERO.is_zero());
1820/// assert!(!4.is_zero());
1821/// ```
1822///
1823/// With an associated type:
1824///
1825/// ```rust
1826/// trait Builder {
1827///     type Built;
1828///
1829///     fn build(&self) -> Self::Built;
1830/// }
1831/// ```
1832///
1833/// Traits can be generic, with constraints or without:
1834///
1835/// ```rust
1836/// trait MaybeFrom<T> {
1837///     fn maybe_from(value: T) -> Option<Self>
1838///     where
1839///         Self: Sized;
1840/// }
1841/// ```
1842///
1843/// Traits can build upon the requirements of other traits. In the example
1844/// below `Iterator` is a **supertrait** and `ThreeIterator` is a **subtrait**:
1845///
1846/// ```rust
1847/// trait ThreeIterator: Iterator {
1848///     fn next_three(&mut self) -> Option<[Self::Item; 3]>;
1849/// }
1850/// ```
1851///
1852/// Traits can be used in functions, as parameters:
1853///
1854/// ```rust
1855/// # #![allow(dead_code)]
1856/// fn debug_iter<I: Iterator>(it: I) where I::Item: std::fmt::Debug {
1857///     for elem in it {
1858///         println!("{elem:#?}");
1859///     }
1860/// }
1861///
1862/// // u8_len_1, u8_len_2 and u8_len_3 are equivalent
1863///
1864/// fn u8_len_1(val: impl Into<Vec<u8>>) -> usize {
1865///     val.into().len()
1866/// }
1867///
1868/// fn u8_len_2<T: Into<Vec<u8>>>(val: T) -> usize {
1869///     val.into().len()
1870/// }
1871///
1872/// fn u8_len_3<T>(val: T) -> usize
1873/// where
1874///     T: Into<Vec<u8>>,
1875/// {
1876///     val.into().len()
1877/// }
1878/// ```
1879///
1880/// Or as return types:
1881///
1882/// ```rust
1883/// # #![allow(dead_code)]
1884/// fn from_zero_to(v: u8) -> impl Iterator<Item = u8> {
1885///     (0..v).into_iter()
1886/// }
1887/// ```
1888///
1889/// The use of the [`impl`] keyword in this position allows the function writer
1890/// to hide the concrete type as an implementation detail which can change
1891/// without breaking user's code.
1892///
1893/// # Trait objects
1894///
1895/// A *trait object* is an opaque value of another type that implements a set of
1896/// traits. A trait object implements all specified traits as well as their
1897/// supertraits (if any).
1898///
1899/// The syntax is the following: `dyn BaseTrait + AutoTrait1 + ... AutoTraitN`.
1900/// Only one `BaseTrait` can be used so this will not compile:
1901///
1902/// ```rust,compile_fail,E0225
1903/// trait A {}
1904/// trait B {}
1905///
1906/// let _: Box<dyn A + B>;
1907/// ```
1908///
1909/// Neither will this, which is a syntax error:
1910///
1911/// ```rust,compile_fail
1912/// trait A {}
1913/// trait B {}
1914///
1915/// let _: Box<dyn A + dyn B>;
1916/// ```
1917///
1918/// On the other hand, this is correct:
1919///
1920/// ```rust
1921/// trait A {}
1922///
1923/// let _: Box<dyn A + Send + Sync>;
1924/// ```
1925///
1926/// The [Reference][Ref-Trait-Objects] has more information about trait objects,
1927/// their limitations and the differences between editions.
1928///
1929/// # Unsafe traits
1930///
1931/// Some traits may be unsafe to implement. Using the [`unsafe`] keyword in
1932/// front of the trait's declaration is used to mark this:
1933///
1934/// ```rust
1935/// unsafe trait UnsafeTrait {}
1936///
1937/// unsafe impl UnsafeTrait for i32 {}
1938/// ```
1939///
1940/// # Differences between the 2015 and 2018 editions
1941///
1942/// In the 2015 edition the parameters pattern was not needed for traits:
1943///
1944/// ```rust,edition2015
1945/// # #![allow(anonymous_parameters)]
1946/// trait Tr {
1947///     fn f(i32);
1948/// }
1949/// ```
1950///
1951/// This behavior is no longer valid in edition 2018.
1952///
1953/// [`for`]: keyword.for.html
1954/// [`impl`]: keyword.impl.html
1955/// [`unsafe`]: keyword.unsafe.html
1956/// [Ref-Traits]: ../reference/items/traits.html
1957/// [Ref-Trait-Objects]: ../reference/types/trait-object.html
1958mod trait_keyword {}
1959
1960#[doc(keyword = "true")]
1961//
1962/// A value of type [`bool`] representing logical **true**.
1963///
1964/// Logically `true` is not equal to [`false`].
1965///
1966/// ## Control structures that check for **true**
1967///
1968/// Several of Rust's control structures will check for a `bool` condition evaluating to **true**.
1969///
1970///   * The condition in an [`if`] expression must be of type `bool`.
1971///     Whenever that condition evaluates to **true**, the `if` expression takes
1972///     on the value of the first block. If however, the condition evaluates
1973///     to `false`, the expression takes on value of the `else` block if there is one.
1974///
1975///   * [`while`] is another control flow construct expecting a `bool`-typed condition.
1976///     As long as the condition evaluates to **true**, the `while` loop will continually
1977///     evaluate its associated block.
1978///
1979///   * [`match`] arms can have guard clauses on them.
1980///
1981/// [`if`]: keyword.if.html
1982/// [`while`]: keyword.while.html
1983/// [`match`]: ../reference/expressions/match-expr.html#match-guards
1984/// [`false`]: keyword.false.html
1985mod true_keyword {}
1986
1987#[doc(keyword = "type")]
1988//
1989/// Define an [alias] for an existing type.
1990///
1991/// The syntax is `type Name = ExistingType;`.
1992///
1993/// # Examples
1994///
1995/// `type` does **not** create a new type:
1996///
1997/// ```rust
1998/// type Meters = u32;
1999/// type Kilograms = u32;
2000///
2001/// let m: Meters = 3;
2002/// let k: Kilograms = 3;
2003///
2004/// assert_eq!(m, k);
2005/// ```
2006///
2007/// A type can be generic:
2008///
2009/// ```rust
2010/// # use std::sync::{Arc, Mutex};
2011/// type ArcMutex<T> = Arc<Mutex<T>>;
2012/// ```
2013///
2014/// In traits, `type` is used to declare an [associated type]:
2015///
2016/// ```rust
2017/// trait Iterator {
2018///     // associated type declaration
2019///     type Item;
2020///     fn next(&mut self) -> Option<Self::Item>;
2021/// }
2022///
2023/// struct Once<T>(Option<T>);
2024///
2025/// impl<T> Iterator for Once<T> {
2026///     // associated type definition
2027///     type Item = T;
2028///     fn next(&mut self) -> Option<Self::Item> {
2029///         self.0.take()
2030///     }
2031/// }
2032/// ```
2033///
2034/// [`trait`]: keyword.trait.html
2035/// [associated type]: ../reference/items/associated-items.html#associated-types
2036/// [alias]: ../reference/items/type-aliases.html
2037mod type_keyword {}
2038
2039#[doc(keyword = "unsafe")]
2040//
2041/// Code or interfaces whose [memory safety] cannot be verified by the type
2042/// system.
2043///
2044/// The `unsafe` keyword has two uses:
2045/// - to declare the existence of contracts the compiler can't check (`unsafe fn` and `unsafe
2046/// trait`),
2047/// - and to declare that a programmer has checked that these contracts have been upheld (`unsafe
2048/// {}` and `unsafe impl`, but also `unsafe fn` -- see below).
2049///
2050/// # Unsafe abilities
2051///
2052/// **No matter what, Safe Rust can't cause Undefined Behavior**. This is
2053/// referred to as [soundness]: a well-typed program actually has the desired
2054/// properties. The [Nomicon][nomicon-soundness] has a more detailed explanation
2055/// on the subject.
2056///
2057/// To ensure soundness, Safe Rust is restricted enough that it can be
2058/// automatically checked. Sometimes, however, it is necessary to write code
2059/// that is correct for reasons which are too clever for the compiler to
2060/// understand. In those cases, you need to use Unsafe Rust.
2061///
2062/// Here are the abilities Unsafe Rust has in addition to Safe Rust:
2063///
2064/// - Dereference [raw pointers]
2065/// - Implement `unsafe` [`trait`]s
2066/// - Call `unsafe` functions
2067/// - Mutate [`static`]s (including [`extern`]al ones)
2068/// - Access fields of [`union`]s
2069///
2070/// However, this extra power comes with extra responsibilities: it is now up to
2071/// you to ensure soundness. The `unsafe` keyword helps by clearly marking the
2072/// pieces of code that need to worry about this.
2073///
2074/// ## The different meanings of `unsafe`
2075///
2076/// Not all uses of `unsafe` are equivalent: some are here to mark the existence
2077/// of a contract the programmer must check, others are to say "I have checked
2078/// the contract, go ahead and do this". The following
2079/// [discussion on Rust Internals] has more in-depth explanations about this but
2080/// here is a summary of the main points:
2081///
2082/// - `unsafe fn`: calling this function means abiding by a contract the
2083/// compiler cannot enforce.
2084/// - `unsafe trait`: implementing the [`trait`] means abiding by a
2085/// contract the compiler cannot enforce.
2086/// - `unsafe {}`: the contract necessary to call the operations inside the
2087/// block has been checked by the programmer and is guaranteed to be respected.
2088/// - `unsafe impl`: the contract necessary to implement the trait has been
2089/// checked by the programmer and is guaranteed to be respected.
2090///
2091/// See the [Rustonomicon] and the [Reference] for more information.
2092///
2093/// # Examples
2094///
2095/// ## Marking elements as `unsafe`
2096///
2097/// `unsafe` can be used on functions. Note that functions and statics declared
2098/// in [`extern`] blocks are implicitly marked as `unsafe` (but not functions
2099/// declared as `extern "something" fn ...`). Mutable statics are always unsafe,
2100/// wherever they are declared. Methods can also be declared as `unsafe`:
2101///
2102/// ```rust
2103/// # #![allow(dead_code)]
2104/// static mut FOO: &str = "hello";
2105///
2106/// unsafe fn unsafe_fn() {}
2107///
2108/// unsafe extern "C" {
2109///     fn unsafe_extern_fn();
2110///     static BAR: *mut u32;
2111/// }
2112///
2113/// trait SafeTraitWithUnsafeMethod {
2114///     unsafe fn unsafe_method(&self);
2115/// }
2116///
2117/// struct S;
2118///
2119/// impl S {
2120///     unsafe fn unsafe_method_on_struct() {}
2121/// }
2122/// ```
2123///
2124/// Traits can also be declared as `unsafe`:
2125///
2126/// ```rust
2127/// unsafe trait UnsafeTrait {}
2128/// ```
2129///
2130/// Since `unsafe fn` and `unsafe trait` indicate that there is a safety
2131/// contract that the compiler cannot enforce, documenting it is important. The
2132/// standard library has many examples of this, like the following which is an
2133/// extract from [`Vec::set_len`]. The `# Safety` section explains the contract
2134/// that must be fulfilled to safely call the function.
2135///
2136/// ```rust,ignore (stub-to-show-doc-example)
2137/// /// Forces the length of the vector to `new_len`.
2138/// ///
2139/// /// This is a low-level operation that maintains none of the normal
2140/// /// invariants of the type. Normally changing the length of a vector
2141/// /// is done using one of the safe operations instead, such as
2142/// /// `truncate`, `resize`, `extend`, or `clear`.
2143/// ///
2144/// /// # Safety
2145/// ///
2146/// /// - `new_len` must be less than or equal to `capacity()`.
2147/// /// - The elements at `old_len..new_len` must be initialized.
2148/// pub unsafe fn set_len(&mut self, new_len: usize)
2149/// ```
2150///
2151/// ## Using `unsafe {}` blocks and `impl`s
2152///
2153/// Performing `unsafe` operations requires an `unsafe {}` block:
2154///
2155/// ```rust
2156/// # #![allow(dead_code)]
2157/// #![deny(unsafe_op_in_unsafe_fn)]
2158///
2159/// /// Dereference the given pointer.
2160/// ///
2161/// /// # Safety
2162/// ///
2163/// /// `ptr` must be aligned and must not be dangling.
2164/// unsafe fn deref_unchecked(ptr: *const i32) -> i32 {
2165///     // SAFETY: the caller is required to ensure that `ptr` is aligned and dereferenceable.
2166///     unsafe { *ptr }
2167/// }
2168///
2169/// let a = 3;
2170/// let b = &a as *const _;
2171/// // SAFETY: `a` has not been dropped and references are always aligned,
2172/// // so `b` is a valid address.
2173/// unsafe { assert_eq!(*b, deref_unchecked(b)); };
2174/// ```
2175///
2176/// ## `unsafe` and traits
2177///
2178/// The interactions of `unsafe` and traits can be surprising, so let us contrast the
2179/// two combinations of safe `fn` in `unsafe trait` and `unsafe fn` in safe trait using two
2180/// examples:
2181///
2182/// ```rust
2183/// /// # Safety
2184/// ///
2185/// /// `make_even` must return an even number.
2186/// unsafe trait MakeEven {
2187///     fn make_even(&self) -> i32;
2188/// }
2189///
2190/// // SAFETY: Our `make_even` always returns something even.
2191/// unsafe impl MakeEven for i32 {
2192///     fn make_even(&self) -> i32 {
2193///         self << 1
2194///     }
2195/// }
2196///
2197/// fn use_make_even(x: impl MakeEven) {
2198///     if x.make_even() % 2 == 1 {
2199///         // SAFETY: this can never happen, because all `MakeEven` implementations
2200///         // ensure that `make_even` returns something even.
2201///         unsafe { std::hint::unreachable_unchecked() };
2202///     }
2203/// }
2204/// ```
2205///
2206/// Note how the safety contract of the trait is upheld by the implementation, and is itself used to
2207/// uphold the safety contract of the unsafe function `unreachable_unchecked` called by
2208/// `use_make_even`. `make_even` itself is a safe function because its *callers* do not have to
2209/// worry about any contract, only the *implementation* of `MakeEven` is required to uphold a
2210/// certain contract. `use_make_even` is safe because it can use the promise made by `MakeEven`
2211/// implementations to uphold the safety contract of the `unsafe fn unreachable_unchecked` it calls.
2212///
2213/// It is also possible to have `unsafe fn` in a regular safe `trait`:
2214///
2215/// ```rust
2216/// # #![feature(never_type)]
2217/// #![deny(unsafe_op_in_unsafe_fn)]
2218///
2219/// trait Indexable {
2220///     const LEN: usize;
2221///
2222///     /// # Safety
2223///     ///
2224///     /// The caller must ensure that `idx < LEN`.
2225///     unsafe fn idx_unchecked(&self, idx: usize) -> i32;
2226/// }
2227///
2228/// // The implementation for `i32` doesn't need to do any contract reasoning.
2229/// impl Indexable for i32 {
2230///     const LEN: usize = 1;
2231///
2232///     /// See `Indexable` for the safety contract.
2233///     unsafe fn idx_unchecked(&self, idx: usize) -> i32 {
2234///         debug_assert_eq!(idx, 0);
2235///         *self
2236///     }
2237/// }
2238///
2239/// // The implementation for arrays exploits the function contract to
2240/// // make use of `get_unchecked` on slices and avoid a run-time check.
2241/// impl Indexable for [i32; 42] {
2242///     const LEN: usize = 42;
2243///
2244///     /// See `Indexable` for the safety contract.
2245///     unsafe fn idx_unchecked(&self, idx: usize) -> i32 {
2246///         // SAFETY: As per this trait's documentation, the caller ensures
2247///         // that `idx < 42`.
2248///         unsafe { *self.get_unchecked(idx) }
2249///     }
2250/// }
2251///
2252/// // The implementation for the never type declares a length of 0,
2253/// // which means `idx_unchecked` can never be called.
2254/// impl Indexable for ! {
2255///     const LEN: usize = 0;
2256///
2257///     /// See `Indexable` for the safety contract.
2258///     unsafe fn idx_unchecked(&self, idx: usize) -> i32 {
2259///         // SAFETY: As per this trait's documentation, the caller ensures
2260///         // that `idx < 0`, which is impossible, so this is dead code.
2261///         unsafe { std::hint::unreachable_unchecked() }
2262///     }
2263/// }
2264///
2265/// fn use_indexable<I: Indexable>(x: I, idx: usize) -> i32 {
2266///     if idx < I::LEN {
2267///         // SAFETY: We have checked that `idx < I::LEN`.
2268///         unsafe { x.idx_unchecked(idx) }
2269///     } else {
2270///         panic!("index out-of-bounds")
2271///     }
2272/// }
2273/// ```
2274///
2275/// This time, `use_indexable` is safe because it uses a run-time check to discharge the safety
2276/// contract of `idx_unchecked`. Implementing `Indexable` is safe because when writing
2277/// `idx_unchecked`, we don't have to worry: our *callers* need to discharge a proof obligation
2278/// (like `use_indexable` does), but the *implementation* of `get_unchecked` has no proof obligation
2279/// to contend with. Of course, the implementation may choose to call other unsafe operations, and
2280/// then it needs an `unsafe` *block* to indicate it discharged the proof obligations of its
2281/// callees. For that purpose it can make use of the contract that all its callers must uphold --
2282/// the fact that `idx < LEN`.
2283///
2284/// Note that unlike normal `unsafe fn`, an `unsafe fn` in a trait implementation does not get to
2285/// just pick an arbitrary safety contract! It *has* to use the safety contract defined by the trait
2286/// (or one with weaker preconditions).
2287///
2288/// Formally speaking, an `unsafe fn` in a trait is a function with *preconditions* that go beyond
2289/// those encoded by the argument types (such as `idx < LEN`), whereas an `unsafe trait` can declare
2290/// that some of its functions have *postconditions* that go beyond those encoded in the return type
2291/// (such as returning an even integer). If a trait needs a function with both extra precondition
2292/// and extra postcondition, then it needs an `unsafe fn` in an `unsafe trait`.
2293///
2294/// [`extern`]: keyword.extern.html
2295/// [`trait`]: keyword.trait.html
2296/// [`static`]: keyword.static.html
2297/// [`union`]: keyword.union.html
2298/// [`impl`]: keyword.impl.html
2299/// [raw pointers]: ../reference/types/pointer.html
2300/// [memory safety]: ../book/ch19-01-unsafe-rust.html
2301/// [Rustonomicon]: ../nomicon/index.html
2302/// [nomicon-soundness]: ../nomicon/safe-unsafe-meaning.html
2303/// [soundness]: https://rust-lang.github.io/unsafe-code-guidelines/glossary.html#soundness-of-code--of-a-library
2304/// [Reference]: ../reference/unsafety.html
2305/// [discussion on Rust Internals]: https://internals.rust-lang.org/t/what-does-unsafe-mean/6696
2306mod unsafe_keyword {}
2307
2308#[doc(keyword = "use")]
2309//
2310/// Import or rename items from other crates or modules, use values under ergonomic clones
2311/// semantic, or specify precise capturing with `use<..>`.
2312///
2313/// ## Importing items
2314///
2315/// The `use` keyword is employed to shorten the path required to refer to a module item.
2316/// The keyword may appear in modules, blocks, and even functions, typically at the top.
2317///
2318/// The most basic usage of the keyword is `use path::to::item;`,
2319/// though a number of convenient shortcuts are supported:
2320///
2321///   * Simultaneously binding a list of paths with a common prefix,
2322///     using the glob-like brace syntax `use a::b::{c, d, e::f, g::h::i};`
2323///   * Simultaneously binding a list of paths with a common prefix and their common parent module,
2324///     using the [`self`] keyword, such as `use a::b::{self, c, d::e};`
2325///   * Rebinding the target name as a new local name, using the syntax `use p::q::r as x;`.
2326///     This can also be used with the last two features: `use a::b::{self as ab, c as abc}`.
2327///   * Binding all paths matching a given prefix,
2328///     using the asterisk wildcard syntax `use a::b::*;`.
2329///   * Nesting groups of the previous features multiple times,
2330///     such as `use a::b::{self as ab, c, d::{*, e::f}};`
2331///   * Reexporting with visibility modifiers such as `pub use a::b;`
2332///   * Importing with `_` to only import the methods of a trait without binding it to a name
2333///     (to avoid conflict for example): `use ::std::io::Read as _;`.
2334///
2335/// Using path qualifiers like [`crate`], [`super`] or [`self`] is supported: `use crate::a::b;`.
2336///
2337/// Note that when the wildcard `*` is used on a type, it does not import its methods (though
2338/// for `enum`s it imports the variants, as shown in the example below).
2339///
2340/// ```compile_fail,edition2018
2341/// enum ExampleEnum {
2342///     VariantA,
2343///     VariantB,
2344/// }
2345///
2346/// impl ExampleEnum {
2347///     fn new() -> Self {
2348///         Self::VariantA
2349///     }
2350/// }
2351///
2352/// use ExampleEnum::*;
2353///
2354/// // Compiles.
2355/// let _ = VariantA;
2356///
2357/// // Does not compile!
2358/// let n = new();
2359/// ```
2360///
2361/// For more information on `use` and paths in general, see the [Reference][ref-use-decls].
2362///
2363/// The differences about paths and the `use` keyword between the 2015 and 2018 editions
2364/// can also be found in the [Reference][ref-use-decls].
2365///
2366/// ## Precise capturing
2367///
2368/// The `use<..>` syntax is used within certain `impl Trait` bounds to control which generic
2369/// parameters are captured. This is important for return-position `impl Trait` (RPIT) types,
2370/// as it affects borrow checking by controlling which generic parameters can be used in the
2371/// hidden type.
2372///
2373/// For example, the following function demonstrates an error without precise capturing in
2374/// Rust 2021 and earlier editions:
2375///
2376/// ```rust,compile_fail,edition2021
2377/// fn f(x: &()) -> impl Sized { x }
2378/// ```
2379///
2380/// By using `use<'_>` for precise capturing, it can be resolved:
2381///
2382/// ```rust
2383/// fn f(x: &()) -> impl Sized + use<'_> { x }
2384/// ```
2385///
2386/// This syntax specifies that the elided lifetime be captured and therefore available for
2387/// use in the hidden type.
2388///
2389/// In Rust 2024, opaque types automatically capture all lifetime parameters in scope.
2390/// `use<..>` syntax serves as an important way of opting-out of that default.
2391///
2392/// For more details about precise capturing, see the [Reference][ref-impl-trait].
2393///
2394/// ## Ergonomic clones
2395///
2396/// Use a values, copying its content if the value implements `Copy`, cloning the contents if the
2397/// value implements `UseCloned` or moving it otherwise.
2398///
2399/// [`crate`]: keyword.crate.html
2400/// [`self`]: keyword.self.html
2401/// [`super`]: keyword.super.html
2402/// [ref-use-decls]: ../reference/items/use-declarations.html
2403/// [ref-impl-trait]: ../reference/types/impl-trait.html
2404mod use_keyword {}
2405
2406#[doc(keyword = "where")]
2407//
2408/// Add constraints that must be upheld to use an item.
2409///
2410/// `where` allows specifying constraints on lifetime and generic parameters.
2411/// The [RFC] introducing `where` contains detailed information about the
2412/// keyword.
2413///
2414/// # Examples
2415///
2416/// `where` can be used for constraints with traits:
2417///
2418/// ```rust
2419/// fn new<T: Default>() -> T {
2420///     T::default()
2421/// }
2422///
2423/// fn new_where<T>() -> T
2424/// where
2425///     T: Default,
2426/// {
2427///     T::default()
2428/// }
2429///
2430/// assert_eq!(0.0, new());
2431/// assert_eq!(0.0, new_where());
2432///
2433/// assert_eq!(0, new());
2434/// assert_eq!(0, new_where());
2435/// ```
2436///
2437/// `where` can also be used for lifetimes.
2438///
2439/// This compiles because `longer` outlives `shorter`, thus the constraint is
2440/// respected:
2441///
2442/// ```rust
2443/// fn select<'short, 'long>(s1: &'short str, s2: &'long str, second: bool) -> &'short str
2444/// where
2445///     'long: 'short,
2446/// {
2447///     if second { s2 } else { s1 }
2448/// }
2449///
2450/// let outer = String::from("Long living ref");
2451/// let longer = &outer;
2452/// {
2453///     let inner = String::from("Short living ref");
2454///     let shorter = &inner;
2455///
2456///     assert_eq!(select(shorter, longer, false), shorter);
2457///     assert_eq!(select(shorter, longer, true), longer);
2458/// }
2459/// ```
2460///
2461/// On the other hand, this will not compile because the `where 'b: 'a` clause
2462/// is missing: the `'b` lifetime is not known to live at least as long as `'a`
2463/// which means this function cannot ensure it always returns a valid reference:
2464///
2465/// ```rust,compile_fail
2466/// fn select<'a, 'b>(s1: &'a str, s2: &'b str, second: bool) -> &'a str
2467/// {
2468///     if second { s2 } else { s1 }
2469/// }
2470/// ```
2471///
2472/// `where` can also be used to express more complicated constraints that cannot
2473/// be written with the `<T: Trait>` syntax:
2474///
2475/// ```rust
2476/// fn first_or_default<I>(mut i: I) -> I::Item
2477/// where
2478///     I: Iterator,
2479///     I::Item: Default,
2480/// {
2481///     i.next().unwrap_or_else(I::Item::default)
2482/// }
2483///
2484/// assert_eq!(first_or_default([1, 2, 3].into_iter()), 1);
2485/// assert_eq!(first_or_default(Vec::<i32>::new().into_iter()), 0);
2486/// ```
2487///
2488/// `where` is available anywhere generic and lifetime parameters are available,
2489/// as can be seen with the [`Cow`](crate::borrow::Cow) type from the standard
2490/// library:
2491///
2492/// ```rust
2493/// # #![allow(dead_code)]
2494/// pub enum Cow<'a, B>
2495/// where
2496///     B: ToOwned + ?Sized,
2497/// {
2498///     Borrowed(&'a B),
2499///     Owned(<B as ToOwned>::Owned),
2500/// }
2501/// ```
2502///
2503/// [RFC]: https://github.com/rust-lang/rfcs/blob/master/text/0135-where.md
2504mod where_keyword {}
2505
2506#[doc(keyword = "while")]
2507//
2508/// Loop while a condition is upheld.
2509///
2510/// A `while` expression is used for predicate loops. The `while` expression runs the conditional
2511/// expression before running the loop body, then runs the loop body if the conditional
2512/// expression evaluates to `true`, or exits the loop otherwise.
2513///
2514/// ```rust
2515/// let mut counter = 0;
2516///
2517/// while counter < 10 {
2518///     println!("{counter}");
2519///     counter += 1;
2520/// }
2521/// ```
2522///
2523/// Like the [`for`] expression, we can use `break` and `continue`. A `while` expression
2524/// cannot break with a value and always evaluates to `()` unlike [`loop`].
2525///
2526/// ```rust
2527/// let mut i = 1;
2528///
2529/// while i < 100 {
2530///     i *= 2;
2531///     if i == 64 {
2532///         break; // Exit when `i` is 64.
2533///     }
2534/// }
2535/// ```
2536///
2537/// As `if` expressions have their pattern matching variant in `if let`, so too do `while`
2538/// expressions with `while let`. The `while let` expression matches the pattern against the
2539/// expression, then runs the loop body if pattern matching succeeds, or exits the loop otherwise.
2540/// We can use `break` and `continue` in `while let` expressions just like in `while`.
2541///
2542/// ```rust
2543/// let mut counter = Some(0);
2544///
2545/// while let Some(i) = counter {
2546///     if i == 10 {
2547///         counter = None;
2548///     } else {
2549///         println!("{i}");
2550///         counter = Some (i + 1);
2551///     }
2552/// }
2553/// ```
2554///
2555/// For more information on `while` and loops in general, see the [reference].
2556///
2557/// See also, [`for`], [`loop`].
2558///
2559/// [`for`]: keyword.for.html
2560/// [`loop`]: keyword.loop.html
2561/// [reference]: ../reference/expressions/loop-expr.html#predicate-loops
2562mod while_keyword {}
2563
2564// 2018 Edition keywords
2565
2566#[doc(alias = "promise")]
2567#[doc(keyword = "async")]
2568//
2569/// Returns a [`Future`] instead of blocking the current thread.
2570///
2571/// Use `async` in front of `fn`, `closure`, or a `block` to turn the marked code into a `Future`.
2572/// As such the code will not be run immediately, but will only be evaluated when the returned
2573/// future is [`.await`]ed.
2574///
2575/// We have written an [async book] detailing `async`/`await` and trade-offs compared to using threads.
2576///
2577/// ## Control Flow
2578/// [`return`] statements and [`?`][try operator] operators within `async` blocks do not cause
2579/// a return from the parent function; rather, they cause the `Future` returned by the block to
2580/// return with that value.
2581///
2582/// For example, the following Rust function will return `5`, causing `x` to take the [`!` type][never type]:
2583/// ```rust
2584/// #[expect(unused_variables)]
2585/// fn example() -> i32 {
2586///     let x = {
2587///         return 5;
2588///     };
2589/// }
2590/// ```
2591/// In contrast, the following asynchronous function assigns a `Future<Output = i32>` to `x`, and
2592/// only returns `5` when `x` is `.await`ed:
2593/// ```rust
2594/// async fn example() -> i32 {
2595///     let x = async {
2596///         return 5;
2597///     };
2598///
2599///     x.await
2600/// }
2601/// ```
2602/// Code using `?` behaves similarly - it causes the `async` block to return a [`Result`] without
2603/// affecting the parent function.
2604///
2605/// Note that you cannot use `break` or `continue` from within an `async` block to affect the
2606/// control flow of a loop in the parent function.
2607///
2608/// Control flow in `async` blocks is documented further in the [async book][async book blocks].
2609///
2610/// ## Editions
2611///
2612/// `async` is a keyword from the 2018 edition onwards.
2613///
2614/// It is available for use in stable Rust from version 1.39 onwards.
2615///
2616/// [`Future`]: future::Future
2617/// [`.await`]: ../std/keyword.await.html
2618/// [async book]: https://rust-lang.github.io/async-book/
2619/// [`return`]: ../std/keyword.return.html
2620/// [try operator]: ../reference/expressions/operator-expr.html#r-expr.try
2621/// [never type]: ../reference/types/never.html
2622/// [`Result`]: result::Result
2623/// [async book blocks]: https://rust-lang.github.io/async-book/part-guide/more-async-await.html#async-blocks
2624mod async_keyword {}
2625
2626#[doc(keyword = "await")]
2627//
2628/// Suspend execution until the result of a [`Future`] is ready.
2629///
2630/// `.await`ing a future will suspend the current function's execution until the executor
2631/// has run the future to completion.
2632///
2633/// Read the [async book] for details on how [`async`]/`await` and executors work.
2634///
2635/// ## Editions
2636///
2637/// `await` is a keyword from the 2018 edition onwards.
2638///
2639/// It is available for use in stable Rust from version 1.39 onwards.
2640///
2641/// [`Future`]: future::Future
2642/// [async book]: https://rust-lang.github.io/async-book/
2643/// [`async`]: ../std/keyword.async.html
2644mod await_keyword {}
2645
2646#[doc(keyword = "dyn")]
2647//
2648/// `dyn` is a prefix of a [trait object]'s type.
2649///
2650/// The `dyn` keyword is used to highlight that calls to methods on the associated `Trait`
2651/// are [dynamically dispatched]. To use the trait this way, it must be *dyn compatible*[^1].
2652///
2653/// Unlike generic parameters or `impl Trait`, the compiler does not know the concrete type that
2654/// is being passed. That is, the type has been [erased].
2655/// As such, a `dyn Trait` reference contains _two_ pointers.
2656/// One pointer goes to the data (e.g., an instance of a struct).
2657/// Another pointer goes to a map of method call names to function pointers
2658/// (known as a virtual method table or vtable).
2659///
2660/// At run-time, when a method needs to be called on the `dyn Trait`, the vtable is consulted to get
2661/// the function pointer and then that function pointer is called.
2662///
2663/// See the Reference for more information on [trait objects][ref-trait-obj]
2664/// and [dyn compatibility][ref-dyn-compat].
2665///
2666/// ## Trade-offs
2667///
2668/// The above indirection is the additional runtime cost of calling a function on a `dyn Trait`.
2669/// Methods called by dynamic dispatch generally cannot be inlined by the compiler.
2670///
2671/// However, `dyn Trait` is likely to produce smaller code than `impl Trait` / generic parameters as
2672/// the method won't be duplicated for each concrete type.
2673///
2674/// [trait object]: ../book/ch17-02-trait-objects.html
2675/// [dynamically dispatched]: https://en.wikipedia.org/wiki/Dynamic_dispatch
2676/// [ref-trait-obj]: ../reference/types/trait-object.html
2677/// [ref-dyn-compat]: ../reference/items/traits.html#dyn-compatibility
2678/// [erased]: https://en.wikipedia.org/wiki/Type_erasure
2679/// [^1]: Formerly known as *object safe*.
2680mod dyn_keyword {}
2681
2682#[doc(keyword = "union")]
2683//
2684/// The [Rust equivalent of a C-style union][union].
2685///
2686/// A `union` looks like a [`struct`] in terms of declaration, but all of its
2687/// fields exist in the same memory, superimposed over one another. For instance,
2688/// if we wanted some bits in memory that we sometimes interpret as a `u32` and
2689/// sometimes as an `f32`, we could write:
2690///
2691/// ```rust
2692/// union IntOrFloat {
2693///     i: u32,
2694///     f: f32,
2695/// }
2696///
2697/// let mut u = IntOrFloat { f: 1.0 };
2698/// // Reading the fields of a union is always unsafe
2699/// assert_eq!(unsafe { u.i }, 1065353216);
2700/// // Updating through any of the field will modify all of them
2701/// u.i = 1073741824;
2702/// assert_eq!(unsafe { u.f }, 2.0);
2703/// ```
2704///
2705/// # Matching on unions
2706///
2707/// It is possible to use pattern matching on `union`s. A single field name must
2708/// be used and it must match the name of one of the `union`'s field.
2709/// Like reading from a `union`, pattern matching on a `union` requires `unsafe`.
2710///
2711/// ```rust
2712/// union IntOrFloat {
2713///     i: u32,
2714///     f: f32,
2715/// }
2716///
2717/// let u = IntOrFloat { f: 1.0 };
2718///
2719/// unsafe {
2720///     match u {
2721///         IntOrFloat { i: 10 } => println!("Found exactly ten!"),
2722///         // Matching the field `f` provides an `f32`.
2723///         IntOrFloat { f } => println!("Found f = {f} !"),
2724///     }
2725/// }
2726/// ```
2727///
2728/// # References to union fields
2729///
2730/// All fields in a `union` are all at the same place in memory which means
2731/// borrowing one borrows the entire `union`, for the same lifetime:
2732///
2733/// ```rust,compile_fail,E0502
2734/// union IntOrFloat {
2735///     i: u32,
2736///     f: f32,
2737/// }
2738///
2739/// let mut u = IntOrFloat { f: 1.0 };
2740///
2741/// let f = unsafe { &u.f };
2742/// // This will not compile because the field has already been borrowed, even
2743/// // if only immutably
2744/// let i = unsafe { &mut u.i };
2745///
2746/// *i = 10;
2747/// println!("f = {f} and i = {i}");
2748/// ```
2749///
2750/// See the [Reference][union] for more information on `union`s.
2751///
2752/// [`struct`]: keyword.struct.html
2753/// [union]: ../reference/items/unions.html
2754mod union_keyword {}