std/
keyword_docs.rs

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