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 = "self")]
1261//
1262/// The receiver of a method, or the current module.
1263///
1264/// `self` is used in two situations: referencing the current module and marking
1265/// the receiver of a method.
1266///
1267/// In paths, `self` can be used to refer to the current module, either in a
1268/// [`use`] statement or in a path to access an element:
1269///
1270/// ```
1271/// # #![allow(unused_imports)]
1272/// use std::io::{self, Read};
1273/// ```
1274///
1275/// Is functionally the same as:
1276///
1277/// ```
1278/// # #![allow(unused_imports)]
1279/// use std::io;
1280/// use std::io::Read;
1281/// ```
1282///
1283/// Using `self` to access an element in the current module:
1284///
1285/// ```
1286/// # #![allow(dead_code)]
1287/// # fn main() {}
1288/// fn foo() {}
1289/// fn bar() {
1290/// self::foo()
1291/// }
1292/// ```
1293///
1294/// `self` as the current receiver for a method allows to omit the parameter
1295/// type most of the time. With the exception of this particularity, `self` is
1296/// used much like any other parameter:
1297///
1298/// ```
1299/// struct Foo(i32);
1300///
1301/// impl Foo {
1302/// // No `self`.
1303/// fn new() -> Self {
1304/// Self(0)
1305/// }
1306///
1307/// // Consuming `self`.
1308/// fn consume(self) -> Self {
1309/// Self(self.0 + 1)
1310/// }
1311///
1312/// // Borrowing `self`.
1313/// fn borrow(&self) -> &i32 {
1314/// &self.0
1315/// }
1316///
1317/// // Borrowing `self` mutably.
1318/// fn borrow_mut(&mut self) -> &mut i32 {
1319/// &mut self.0
1320/// }
1321/// }
1322///
1323/// // This method must be called with a `Type::` prefix.
1324/// let foo = Foo::new();
1325/// assert_eq!(foo.0, 0);
1326///
1327/// // Those two calls produces the same result.
1328/// let foo = Foo::consume(foo);
1329/// assert_eq!(foo.0, 1);
1330/// let foo = foo.consume();
1331/// assert_eq!(foo.0, 2);
1332///
1333/// // Borrowing is handled automatically with the second syntax.
1334/// let borrow_1 = Foo::borrow(&foo);
1335/// let borrow_2 = foo.borrow();
1336/// assert_eq!(borrow_1, borrow_2);
1337///
1338/// // Borrowing mutably is handled automatically too with the second syntax.
1339/// let mut foo = Foo::new();
1340/// *Foo::borrow_mut(&mut foo) += 1;
1341/// assert_eq!(foo.0, 1);
1342/// *foo.borrow_mut() += 1;
1343/// assert_eq!(foo.0, 2);
1344/// ```
1345///
1346/// Note that this automatic conversion when calling `foo.method()` is not
1347/// limited to the examples above. See the [Reference] for more information.
1348///
1349/// [`use`]: keyword.use.html
1350/// [Reference]: ../reference/items/associated-items.html#methods
1351mod self_keyword {}
1352
1353// FIXME: Once rustdoc can handle URL conflicts on case insensitive file systems, we can replace
1354// these two lines with `#[doc(keyword = "Self")]` and update `is_doc_keyword` in
1355// `CheckAttrVisitor`.
1356#[doc(alias = "Self")]
1357#[doc(keyword = "SelfTy")]
1358//
1359/// The implementing type within a [`trait`] or [`impl`] block, or the current type within a type
1360/// definition.
1361///
1362/// Within a type definition:
1363///
1364/// ```
1365/// # #![allow(dead_code)]
1366/// struct Node {
1367/// elem: i32,
1368/// // `Self` is a `Node` here.
1369/// next: Option<Box<Self>>,
1370/// }
1371/// ```
1372///
1373/// In an [`impl`] block:
1374///
1375/// ```
1376/// struct Foo(i32);
1377///
1378/// impl Foo {
1379/// fn new() -> Self {
1380/// Self(0)
1381/// }
1382/// }
1383///
1384/// assert_eq!(Foo::new().0, Foo(0).0);
1385/// ```
1386///
1387/// Generic parameters are implicit with `Self`:
1388///
1389/// ```
1390/// # #![allow(dead_code)]
1391/// struct Wrap<T> {
1392/// elem: T,
1393/// }
1394///
1395/// impl<T> Wrap<T> {
1396/// fn new(elem: T) -> Self {
1397/// Self { elem }
1398/// }
1399/// }
1400/// ```
1401///
1402/// In a [`trait`] definition and related [`impl`] block:
1403///
1404/// ```
1405/// trait Example {
1406/// fn example() -> Self;
1407/// }
1408///
1409/// struct Foo(i32);
1410///
1411/// impl Example for Foo {
1412/// fn example() -> Self {
1413/// Self(42)
1414/// }
1415/// }
1416///
1417/// assert_eq!(Foo::example().0, Foo(42).0);
1418/// ```
1419///
1420/// [`impl`]: keyword.impl.html
1421/// [`trait`]: keyword.trait.html
1422mod self_upper_keyword {}
1423
1424#[doc(keyword = "static")]
1425//
1426/// A static item is a value which is valid for the entire duration of your
1427/// program (a `'static` lifetime).
1428///
1429/// On the surface, `static` items seem very similar to [`const`]s: both contain
1430/// a value, both require type annotations and both can only be initialized with
1431/// constant functions and values. However, `static`s are notably different in
1432/// that they represent a location in memory. That means that you can have
1433/// references to `static` items and potentially even modify them, making them
1434/// essentially global variables.
1435///
1436/// Static items do not call [`drop`] at the end of the program.
1437///
1438/// There are two types of `static` items: those declared in association with
1439/// the [`mut`] keyword and those without.
1440///
1441/// Static items cannot be moved:
1442///
1443/// ```rust,compile_fail,E0507
1444/// static VEC: Vec<u32> = vec![];
1445///
1446/// fn move_vec(v: Vec<u32>) -> Vec<u32> {
1447/// v
1448/// }
1449///
1450/// // This line causes an error
1451/// move_vec(VEC);
1452/// ```
1453///
1454/// # Simple `static`s
1455///
1456/// Accessing non-[`mut`] `static` items is considered safe, but some
1457/// restrictions apply. Most notably, the type of a `static` value needs to
1458/// implement the [`Sync`] trait, ruling out interior mutability containers
1459/// like [`RefCell`]. See the [Reference] for more information.
1460///
1461/// ```rust
1462/// static FOO: [i32; 5] = [1, 2, 3, 4, 5];
1463///
1464/// let r1 = &FOO as *const _;
1465/// let r2 = &FOO as *const _;
1466/// // With a strictly read-only static, references will have the same address
1467/// assert_eq!(r1, r2);
1468/// // A static item can be used just like a variable in many cases
1469/// println!("{FOO:?}");
1470/// ```
1471///
1472/// # Mutable `static`s
1473///
1474/// If a `static` item is declared with the [`mut`] keyword, then it is allowed
1475/// to be modified by the program. However, accessing mutable `static`s can
1476/// cause undefined behavior in a number of ways, for example due to data races
1477/// in a multithreaded context. As such, all accesses to mutable `static`s
1478/// require an [`unsafe`] block.
1479///
1480/// When possible, it's often better to use a non-mutable `static` with an
1481/// interior mutable type such as [`Mutex`], [`OnceLock`], or an [atomic].
1482///
1483/// Despite their unsafety, mutable `static`s are necessary in many contexts:
1484/// they can be used to represent global state shared by the whole program or in
1485/// [`extern`] blocks to bind to variables from C libraries.
1486///
1487/// In an [`extern`] block:
1488///
1489/// ```rust,no_run
1490/// # #![allow(dead_code)]
1491/// unsafe extern "C" {
1492/// static mut ERROR_MESSAGE: *mut std::os::raw::c_char;
1493/// }
1494/// ```
1495///
1496/// Mutable `static`s, just like simple `static`s, have some restrictions that
1497/// apply to them. See the [Reference] for more information.
1498///
1499/// [`const`]: keyword.const.html
1500/// [`extern`]: keyword.extern.html
1501/// [`mut`]: keyword.mut.html
1502/// [`unsafe`]: keyword.unsafe.html
1503/// [`Mutex`]: sync::Mutex
1504/// [`OnceLock`]: sync::OnceLock
1505/// [`RefCell`]: cell::RefCell
1506/// [atomic]: sync::atomic
1507/// [Reference]: ../reference/items/static-items.html
1508mod static_keyword {}
1509
1510#[doc(keyword = "struct")]
1511//
1512/// A type that is composed of other types.
1513///
1514/// Structs in Rust come in three flavors: Structs with named fields, tuple structs, and unit
1515/// structs.
1516///
1517/// ```rust
1518/// struct Regular {
1519/// field1: f32,
1520/// field2: String,
1521/// pub field3: bool
1522/// }
1523///
1524/// struct Tuple(u32, String);
1525///
1526/// struct Unit;
1527/// ```
1528///
1529/// Regular structs are the most commonly used. Each field defined within them has a name and a
1530/// type, and once defined can be accessed using `example_struct.field` syntax. The fields of a
1531/// struct share its mutability, so `foo.bar = 2;` would only be valid if `foo` was mutable. Adding
1532/// `pub` to a field makes it visible to code in other modules, as well as allowing it to be
1533/// directly accessed and modified.
1534///
1535/// Tuple structs are similar to regular structs, but its fields have no names. They are used like
1536/// tuples, with deconstruction possible via `let TupleStruct(x, y) = foo;` syntax. For accessing
1537/// individual variables, the same syntax is used as with regular tuples, namely `foo.0`, `foo.1`,
1538/// etc, starting at zero.
1539///
1540/// Unit structs are most commonly used as marker. They have a size of zero bytes, but unlike empty
1541/// enums they can be instantiated, making them isomorphic to the unit type `()`. Unit structs are
1542/// useful when you need to implement a trait on something, but don't need to store any data inside
1543/// it.
1544///
1545/// # Instantiation
1546///
1547/// Structs can be instantiated in different ways, all of which can be mixed and
1548/// matched as needed. The most common way to make a new struct is via a constructor method such as
1549/// `new()`, but when that isn't available (or you're writing the constructor itself), struct
1550/// literal syntax is used:
1551///
1552/// ```rust
1553/// # struct Foo { field1: f32, field2: String, etc: bool }
1554/// let example = Foo {
1555/// field1: 42.0,
1556/// field2: "blah".to_string(),
1557/// etc: true,
1558/// };
1559/// ```
1560///
1561/// It's only possible to directly instantiate a struct using struct literal syntax when all of its
1562/// fields are visible to you.
1563///
1564/// There are a handful of shortcuts provided to make writing constructors more convenient, most
1565/// common of which is the Field Init shorthand. When there is a variable and a field of the same
1566/// name, the assignment can be simplified from `field: field` into simply `field`. The following
1567/// example of a hypothetical constructor demonstrates this:
1568///
1569/// ```rust
1570/// struct User {
1571/// name: String,
1572/// admin: bool,
1573/// }
1574///
1575/// impl User {
1576/// pub fn new(name: String) -> Self {
1577/// Self {
1578/// name,
1579/// admin: false,
1580/// }
1581/// }
1582/// }
1583/// ```
1584///
1585/// Another shortcut for struct instantiation is available, used when you need to make a new
1586/// struct that has the same values as most of a previous struct of the same type, called struct
1587/// update syntax:
1588///
1589/// ```rust
1590/// # struct Foo { field1: String, field2: () }
1591/// # let thing = Foo { field1: "".to_string(), field2: () };
1592/// let updated_thing = Foo {
1593/// field1: "a new value".to_string(),
1594/// ..thing
1595/// };
1596/// ```
1597///
1598/// Tuple structs are instantiated in the same way as tuples themselves, except with the struct's
1599/// name as a prefix: `Foo(123, false, 0.1)`.
1600///
1601/// Empty structs are instantiated with just their name, and don't need anything else. `let thing =
1602/// EmptyStruct;`
1603///
1604/// # Style conventions
1605///
1606/// Structs are always written in UpperCamelCase, with few exceptions. While the trailing comma on a
1607/// struct's list of fields can be omitted, it's usually kept for convenience in adding and
1608/// removing fields down the line.
1609///
1610/// For more information on structs, take a look at the [Rust Book][book] or the
1611/// [Reference][reference].
1612///
1613/// [`PhantomData`]: marker::PhantomData
1614/// [book]: ../book/ch05-01-defining-structs.html
1615/// [reference]: ../reference/items/structs.html
1616mod struct_keyword {}
1617
1618#[doc(keyword = "super")]
1619//
1620/// The parent of the current [module].
1621///
1622/// ```rust
1623/// # #![allow(dead_code)]
1624/// # fn main() {}
1625/// mod a {
1626/// pub fn foo() {}
1627/// }
1628/// mod b {
1629/// pub fn foo() {
1630/// super::a::foo(); // call a's foo function
1631/// }
1632/// }
1633/// ```
1634///
1635/// It is also possible to use `super` multiple times: `super::super::foo`,
1636/// going up the ancestor chain.
1637///
1638/// See the [Reference] for more information.
1639///
1640/// [module]: ../reference/items/modules.html
1641/// [Reference]: ../reference/paths.html#super
1642mod super_keyword {}
1643
1644#[doc(keyword = "trait")]
1645//
1646/// A common interface for a group of types.
1647///
1648/// A `trait` is like an interface that data types can implement. When a type
1649/// implements a trait it can be treated abstractly as that trait using generics
1650/// or trait objects.
1651///
1652/// Traits can be made up of three varieties of associated items:
1653///
1654/// - functions and methods
1655/// - types
1656/// - constants
1657///
1658/// Traits may also contain additional type parameters. Those type parameters
1659/// or the trait itself can be constrained by other traits.
1660///
1661/// Traits can serve as markers or carry other logical semantics that
1662/// aren't expressed through their items. When a type implements that
1663/// trait it is promising to uphold its contract. [`Send`] and [`Sync`] are two
1664/// such marker traits present in the standard library.
1665///
1666/// See the [Reference][Ref-Traits] for a lot more information on traits.
1667///
1668/// # Examples
1669///
1670/// Traits are declared using the `trait` keyword. Types can implement them
1671/// using [`impl`] `Trait` [`for`] `Type`:
1672///
1673/// ```rust
1674/// trait Zero {
1675/// const ZERO: Self;
1676/// fn is_zero(&self) -> bool;
1677/// }
1678///
1679/// impl Zero for i32 {
1680/// const ZERO: Self = 0;
1681///
1682/// fn is_zero(&self) -> bool {
1683/// *self == Self::ZERO
1684/// }
1685/// }
1686///
1687/// assert_eq!(i32::ZERO, 0);
1688/// assert!(i32::ZERO.is_zero());
1689/// assert!(!4.is_zero());
1690/// ```
1691///
1692/// With an associated type:
1693///
1694/// ```rust
1695/// trait Builder {
1696/// type Built;
1697///
1698/// fn build(&self) -> Self::Built;
1699/// }
1700/// ```
1701///
1702/// Traits can be generic, with constraints or without:
1703///
1704/// ```rust
1705/// trait MaybeFrom<T> {
1706/// fn maybe_from(value: T) -> Option<Self>
1707/// where
1708/// Self: Sized;
1709/// }
1710/// ```
1711///
1712/// Traits can build upon the requirements of other traits. In the example
1713/// below `Iterator` is a **supertrait** and `ThreeIterator` is a **subtrait**:
1714///
1715/// ```rust
1716/// trait ThreeIterator: Iterator {
1717/// fn next_three(&mut self) -> Option<[Self::Item; 3]>;
1718/// }
1719/// ```
1720///
1721/// Traits can be used in functions, as parameters:
1722///
1723/// ```rust
1724/// # #![allow(dead_code)]
1725/// fn debug_iter<I: Iterator>(it: I) where I::Item: std::fmt::Debug {
1726/// for elem in it {
1727/// println!("{elem:#?}");
1728/// }
1729/// }
1730///
1731/// // u8_len_1, u8_len_2 and u8_len_3 are equivalent
1732///
1733/// fn u8_len_1(val: impl Into<Vec<u8>>) -> usize {
1734/// val.into().len()
1735/// }
1736///
1737/// fn u8_len_2<T: Into<Vec<u8>>>(val: T) -> usize {
1738/// val.into().len()
1739/// }
1740///
1741/// fn u8_len_3<T>(val: T) -> usize
1742/// where
1743/// T: Into<Vec<u8>>,
1744/// {
1745/// val.into().len()
1746/// }
1747/// ```
1748///
1749/// Or as return types:
1750///
1751/// ```rust
1752/// # #![allow(dead_code)]
1753/// fn from_zero_to(v: u8) -> impl Iterator<Item = u8> {
1754/// (0..v).into_iter()
1755/// }
1756/// ```
1757///
1758/// The use of the [`impl`] keyword in this position allows the function writer
1759/// to hide the concrete type as an implementation detail which can change
1760/// without breaking user's code.
1761///
1762/// # Trait objects
1763///
1764/// A *trait object* is an opaque value of another type that implements a set of
1765/// traits. A trait object implements all specified traits as well as their
1766/// supertraits (if any).
1767///
1768/// The syntax is the following: `dyn BaseTrait + AutoTrait1 + ... AutoTraitN`.
1769/// Only one `BaseTrait` can be used so this will not compile:
1770///
1771/// ```rust,compile_fail,E0225
1772/// trait A {}
1773/// trait B {}
1774///
1775/// let _: Box<dyn A + B>;
1776/// ```
1777///
1778/// Neither will this, which is a syntax error:
1779///
1780/// ```rust,compile_fail
1781/// trait A {}
1782/// trait B {}
1783///
1784/// let _: Box<dyn A + dyn B>;
1785/// ```
1786///
1787/// On the other hand, this is correct:
1788///
1789/// ```rust
1790/// trait A {}
1791///
1792/// let _: Box<dyn A + Send + Sync>;
1793/// ```
1794///
1795/// The [Reference][Ref-Trait-Objects] has more information about trait objects,
1796/// their limitations and the differences between editions.
1797///
1798/// # Unsafe traits
1799///
1800/// Some traits may be unsafe to implement. Using the [`unsafe`] keyword in
1801/// front of the trait's declaration is used to mark this:
1802///
1803/// ```rust
1804/// unsafe trait UnsafeTrait {}
1805///
1806/// unsafe impl UnsafeTrait for i32 {}
1807/// ```
1808///
1809/// # Differences between the 2015 and 2018 editions
1810///
1811/// In the 2015 edition the parameters pattern was not needed for traits:
1812///
1813/// ```rust,edition2015
1814/// # #![allow(anonymous_parameters)]
1815/// trait Tr {
1816/// fn f(i32);
1817/// }
1818/// ```
1819///
1820/// This behavior is no longer valid in edition 2018.
1821///
1822/// [`for`]: keyword.for.html
1823/// [`impl`]: keyword.impl.html
1824/// [`unsafe`]: keyword.unsafe.html
1825/// [Ref-Traits]: ../reference/items/traits.html
1826/// [Ref-Trait-Objects]: ../reference/types/trait-object.html
1827mod trait_keyword {}
1828
1829#[doc(keyword = "true")]
1830//
1831/// A value of type [`bool`] representing logical **true**.
1832///
1833/// Logically `true` is not equal to [`false`].
1834///
1835/// ## Control structures that check for **true**
1836///
1837/// Several of Rust's control structures will check for a `bool` condition evaluating to **true**.
1838///
1839/// * The condition in an [`if`] expression must be of type `bool`.
1840/// Whenever that condition evaluates to **true**, the `if` expression takes
1841/// on the value of the first block. If however, the condition evaluates
1842/// to `false`, the expression takes on value of the `else` block if there is one.
1843///
1844/// * [`while`] is another control flow construct expecting a `bool`-typed condition.
1845/// As long as the condition evaluates to **true**, the `while` loop will continually
1846/// evaluate its associated block.
1847///
1848/// * [`match`] arms can have guard clauses on them.
1849///
1850/// [`if`]: keyword.if.html
1851/// [`while`]: keyword.while.html
1852/// [`match`]: ../reference/expressions/match-expr.html#match-guards
1853/// [`false`]: keyword.false.html
1854mod true_keyword {}
1855
1856#[doc(keyword = "type")]
1857//
1858/// Define an [alias] for an existing type.
1859///
1860/// The syntax is `type Name = ExistingType;`.
1861///
1862/// # Examples
1863///
1864/// `type` does **not** create a new type:
1865///
1866/// ```rust
1867/// type Meters = u32;
1868/// type Kilograms = u32;
1869///
1870/// let m: Meters = 3;
1871/// let k: Kilograms = 3;
1872///
1873/// assert_eq!(m, k);
1874/// ```
1875///
1876/// A type can be generic:
1877///
1878/// ```rust
1879/// # use std::sync::{Arc, Mutex};
1880/// type ArcMutex<T> = Arc<Mutex<T>>;
1881/// ```
1882///
1883/// In traits, `type` is used to declare an [associated type]:
1884///
1885/// ```rust
1886/// trait Iterator {
1887/// // associated type declaration
1888/// type Item;
1889/// fn next(&mut self) -> Option<Self::Item>;
1890/// }
1891///
1892/// struct Once<T>(Option<T>);
1893///
1894/// impl<T> Iterator for Once<T> {
1895/// // associated type definition
1896/// type Item = T;
1897/// fn next(&mut self) -> Option<Self::Item> {
1898/// self.0.take()
1899/// }
1900/// }
1901/// ```
1902///
1903/// [`trait`]: keyword.trait.html
1904/// [associated type]: ../reference/items/associated-items.html#associated-types
1905/// [alias]: ../reference/items/type-aliases.html
1906mod type_keyword {}
1907
1908#[doc(keyword = "unsafe")]
1909//
1910/// Code or interfaces whose [memory safety] cannot be verified by the type
1911/// system.
1912///
1913/// The `unsafe` keyword has two uses:
1914/// - to declare the existence of contracts the compiler can't check (`unsafe fn` and `unsafe
1915/// trait`),
1916/// - and to declare that a programmer has checked that these contracts have been upheld (`unsafe
1917/// {}` and `unsafe impl`, but also `unsafe fn` -- see below).
1918///
1919/// They are not mutually exclusive, as can be seen in `unsafe fn`: the body of an `unsafe fn` is,
1920/// by default, treated like an unsafe block. The `unsafe_op_in_unsafe_fn` lint can be enabled to
1921/// change that.
1922///
1923/// # Unsafe abilities
1924///
1925/// **No matter what, Safe Rust can't cause Undefined Behavior**. This is
1926/// referred to as [soundness]: a well-typed program actually has the desired
1927/// properties. The [Nomicon][nomicon-soundness] has a more detailed explanation
1928/// on the subject.
1929///
1930/// To ensure soundness, Safe Rust is restricted enough that it can be
1931/// automatically checked. Sometimes, however, it is necessary to write code
1932/// that is correct for reasons which are too clever for the compiler to
1933/// understand. In those cases, you need to use Unsafe Rust.
1934///
1935/// Here are the abilities Unsafe Rust has in addition to Safe Rust:
1936///
1937/// - Dereference [raw pointers]
1938/// - Implement `unsafe` [`trait`]s
1939/// - Call `unsafe` functions
1940/// - Mutate [`static`]s (including [`extern`]al ones)
1941/// - Access fields of [`union`]s
1942///
1943/// However, this extra power comes with extra responsibilities: it is now up to
1944/// you to ensure soundness. The `unsafe` keyword helps by clearly marking the
1945/// pieces of code that need to worry about this.
1946///
1947/// ## The different meanings of `unsafe`
1948///
1949/// Not all uses of `unsafe` are equivalent: some are here to mark the existence
1950/// of a contract the programmer must check, others are to say "I have checked
1951/// the contract, go ahead and do this". The following
1952/// [discussion on Rust Internals] has more in-depth explanations about this but
1953/// here is a summary of the main points:
1954///
1955/// - `unsafe fn`: calling this function means abiding by a contract the
1956/// compiler cannot enforce.
1957/// - `unsafe trait`: implementing the [`trait`] means abiding by a
1958/// contract the compiler cannot enforce.
1959/// - `unsafe {}`: the contract necessary to call the operations inside the
1960/// block has been checked by the programmer and is guaranteed to be respected.
1961/// - `unsafe impl`: the contract necessary to implement the trait has been
1962/// checked by the programmer and is guaranteed to be respected.
1963///
1964/// By default, `unsafe fn` also acts like an `unsafe {}` block
1965/// around the code inside the function. This means it is not just a signal to
1966/// the caller, but also promises that the preconditions for the operations
1967/// inside the function are upheld. Mixing these two meanings can be confusing, so the
1968/// `unsafe_op_in_unsafe_fn` lint can be enabled to warn against that and require explicit unsafe
1969/// blocks even inside `unsafe fn`.
1970///
1971/// See the [Rustonomicon] and the [Reference] for more information.
1972///
1973/// # Examples
1974///
1975/// ## Marking elements as `unsafe`
1976///
1977/// `unsafe` can be used on functions. Note that functions and statics declared
1978/// in [`extern`] blocks are implicitly marked as `unsafe` (but not functions
1979/// declared as `extern "something" fn ...`). Mutable statics are always unsafe,
1980/// wherever they are declared. Methods can also be declared as `unsafe`:
1981///
1982/// ```rust
1983/// # #![allow(dead_code)]
1984/// static mut FOO: &str = "hello";
1985///
1986/// unsafe fn unsafe_fn() {}
1987///
1988/// unsafe extern "C" {
1989/// fn unsafe_extern_fn();
1990/// static BAR: *mut u32;
1991/// }
1992///
1993/// trait SafeTraitWithUnsafeMethod {
1994/// unsafe fn unsafe_method(&self);
1995/// }
1996///
1997/// struct S;
1998///
1999/// impl S {
2000/// unsafe fn unsafe_method_on_struct() {}
2001/// }
2002/// ```
2003///
2004/// Traits can also be declared as `unsafe`:
2005///
2006/// ```rust
2007/// unsafe trait UnsafeTrait {}
2008/// ```
2009///
2010/// Since `unsafe fn` and `unsafe trait` indicate that there is a safety
2011/// contract that the compiler cannot enforce, documenting it is important. The
2012/// standard library has many examples of this, like the following which is an
2013/// extract from [`Vec::set_len`]. The `# Safety` section explains the contract
2014/// that must be fulfilled to safely call the function.
2015///
2016/// ```rust,ignore (stub-to-show-doc-example)
2017/// /// Forces the length of the vector to `new_len`.
2018/// ///
2019/// /// This is a low-level operation that maintains none of the normal
2020/// /// invariants of the type. Normally changing the length of a vector
2021/// /// is done using one of the safe operations instead, such as
2022/// /// `truncate`, `resize`, `extend`, or `clear`.
2023/// ///
2024/// /// # Safety
2025/// ///
2026/// /// - `new_len` must be less than or equal to `capacity()`.
2027/// /// - The elements at `old_len..new_len` must be initialized.
2028/// pub unsafe fn set_len(&mut self, new_len: usize)
2029/// ```
2030///
2031/// ## Using `unsafe {}` blocks and `impl`s
2032///
2033/// Performing `unsafe` operations requires an `unsafe {}` block:
2034///
2035/// ```rust
2036/// # #![allow(dead_code)]
2037/// #![deny(unsafe_op_in_unsafe_fn)]
2038///
2039/// /// Dereference the given pointer.
2040/// ///
2041/// /// # Safety
2042/// ///
2043/// /// `ptr` must be aligned and must not be dangling.
2044/// unsafe fn deref_unchecked(ptr: *const i32) -> i32 {
2045/// // SAFETY: the caller is required to ensure that `ptr` is aligned and dereferenceable.
2046/// unsafe { *ptr }
2047/// }
2048///
2049/// let a = 3;
2050/// let b = &a as *const _;
2051/// // SAFETY: `a` has not been dropped and references are always aligned,
2052/// // so `b` is a valid address.
2053/// unsafe { assert_eq!(*b, deref_unchecked(b)); };
2054/// ```
2055///
2056/// ## `unsafe` and traits
2057///
2058/// The interactions of `unsafe` and traits can be surprising, so let us contrast the
2059/// two combinations of safe `fn` in `unsafe trait` and `unsafe fn` in safe trait using two
2060/// examples:
2061///
2062/// ```rust
2063/// /// # Safety
2064/// ///
2065/// /// `make_even` must return an even number.
2066/// unsafe trait MakeEven {
2067/// fn make_even(&self) -> i32;
2068/// }
2069///
2070/// // SAFETY: Our `make_even` always returns something even.
2071/// unsafe impl MakeEven for i32 {
2072/// fn make_even(&self) -> i32 {
2073/// self << 1
2074/// }
2075/// }
2076///
2077/// fn use_make_even(x: impl MakeEven) {
2078/// if x.make_even() % 2 == 1 {
2079/// // SAFETY: this can never happen, because all `MakeEven` implementations
2080/// // ensure that `make_even` returns something even.
2081/// unsafe { std::hint::unreachable_unchecked() };
2082/// }
2083/// }
2084/// ```
2085///
2086/// Note how the safety contract of the trait is upheld by the implementation, and is itself used to
2087/// uphold the safety contract of the unsafe function `unreachable_unchecked` called by
2088/// `use_make_even`. `make_even` itself is a safe function because its *callers* do not have to
2089/// worry about any contract, only the *implementation* of `MakeEven` is required to uphold a
2090/// certain contract. `use_make_even` is safe because it can use the promise made by `MakeEven`
2091/// implementations to uphold the safety contract of the `unsafe fn unreachable_unchecked` it calls.
2092///
2093/// It is also possible to have `unsafe fn` in a regular safe `trait`:
2094///
2095/// ```rust
2096/// # #![feature(never_type)]
2097/// #![deny(unsafe_op_in_unsafe_fn)]
2098///
2099/// trait Indexable {
2100/// const LEN: usize;
2101///
2102/// /// # Safety
2103/// ///
2104/// /// The caller must ensure that `idx < LEN`.
2105/// unsafe fn idx_unchecked(&self, idx: usize) -> i32;
2106/// }
2107///
2108/// // The implementation for `i32` doesn't need to do any contract reasoning.
2109/// impl Indexable for i32 {
2110/// const LEN: usize = 1;
2111///
2112/// unsafe fn idx_unchecked(&self, idx: usize) -> i32 {
2113/// debug_assert_eq!(idx, 0);
2114/// *self
2115/// }
2116/// }
2117///
2118/// // The implementation for arrays exploits the function contract to
2119/// // make use of `get_unchecked` on slices and avoid a run-time check.
2120/// impl Indexable for [i32; 42] {
2121/// const LEN: usize = 42;
2122///
2123/// unsafe fn idx_unchecked(&self, idx: usize) -> i32 {
2124/// // SAFETY: As per this trait's documentation, the caller ensures
2125/// // that `idx < 42`.
2126/// unsafe { *self.get_unchecked(idx) }
2127/// }
2128/// }
2129///
2130/// // The implementation for the never type declares a length of 0,
2131/// // which means `idx_unchecked` can never be called.
2132/// impl Indexable for ! {
2133/// const LEN: usize = 0;
2134///
2135/// unsafe fn idx_unchecked(&self, idx: usize) -> i32 {
2136/// // SAFETY: As per this trait's documentation, the caller ensures
2137/// // that `idx < 0`, which is impossible, so this is dead code.
2138/// unsafe { std::hint::unreachable_unchecked() }
2139/// }
2140/// }
2141///
2142/// fn use_indexable<I: Indexable>(x: I, idx: usize) -> i32 {
2143/// if idx < I::LEN {
2144/// // SAFETY: We have checked that `idx < I::LEN`.
2145/// unsafe { x.idx_unchecked(idx) }
2146/// } else {
2147/// panic!("index out-of-bounds")
2148/// }
2149/// }
2150/// ```
2151///
2152/// This time, `use_indexable` is safe because it uses a run-time check to discharge the safety
2153/// contract of `idx_unchecked`. Implementing `Indexable` is safe because when writing
2154/// `idx_unchecked`, we don't have to worry: our *callers* need to discharge a proof obligation
2155/// (like `use_indexable` does), but the *implementation* of `get_unchecked` has no proof obligation
2156/// to contend with. Of course, the implementation of `Indexable` may choose to call other unsafe
2157/// operations, and then it needs an `unsafe` *block* to indicate it discharged the proof
2158/// obligations of its callees. (We enabled `unsafe_op_in_unsafe_fn`, so the body of `idx_unchecked`
2159/// is not implicitly an unsafe block.) For that purpose it can make use of the contract that all
2160/// its callers must uphold -- the fact that `idx < LEN`.
2161///
2162/// Formally speaking, an `unsafe fn` in a trait is a function with *preconditions* that go beyond
2163/// those encoded by the argument types (such as `idx < LEN`), whereas an `unsafe trait` can declare
2164/// that some of its functions have *postconditions* that go beyond those encoded in the return type
2165/// (such as returning an even integer). If a trait needs a function with both extra precondition
2166/// and extra postcondition, then it needs an `unsafe fn` in an `unsafe trait`.
2167///
2168/// [`extern`]: keyword.extern.html
2169/// [`trait`]: keyword.trait.html
2170/// [`static`]: keyword.static.html
2171/// [`union`]: keyword.union.html
2172/// [`impl`]: keyword.impl.html
2173/// [raw pointers]: ../reference/types/pointer.html
2174/// [memory safety]: ../book/ch19-01-unsafe-rust.html
2175/// [Rustonomicon]: ../nomicon/index.html
2176/// [nomicon-soundness]: ../nomicon/safe-unsafe-meaning.html
2177/// [soundness]: https://rust-lang.github.io/unsafe-code-guidelines/glossary.html#soundness-of-code--of-a-library
2178/// [Reference]: ../reference/unsafety.html
2179/// [discussion on Rust Internals]: https://internals.rust-lang.org/t/what-does-unsafe-mean/6696
2180mod unsafe_keyword {}
2181
2182#[doc(keyword = "use")]
2183//
2184/// Import or rename items from other crates or modules, use values under ergonomic clones
2185/// semantic, or specify precise capturing with `use<..>`.
2186///
2187/// ## Importing items
2188///
2189/// The `use` keyword is employed to shorten the path required to refer to a module item.
2190/// The keyword may appear in modules, blocks, and even functions, typically at the top.
2191///
2192/// The most basic usage of the keyword is `use path::to::item;`,
2193/// though a number of convenient shortcuts are supported:
2194///
2195/// * Simultaneously binding a list of paths with a common prefix,
2196/// using the glob-like brace syntax `use a::b::{c, d, e::f, g::h::i};`
2197/// * Simultaneously binding a list of paths with a common prefix and their common parent module,
2198/// using the [`self`] keyword, such as `use a::b::{self, c, d::e};`
2199/// * Rebinding the target name as a new local name, using the syntax `use p::q::r as x;`.
2200/// This can also be used with the last two features: `use a::b::{self as ab, c as abc}`.
2201/// * Binding all paths matching a given prefix,
2202/// using the asterisk wildcard syntax `use a::b::*;`.
2203/// * Nesting groups of the previous features multiple times,
2204/// such as `use a::b::{self as ab, c, d::{*, e::f}};`
2205/// * Reexporting with visibility modifiers such as `pub use a::b;`
2206/// * Importing with `_` to only import the methods of a trait without binding it to a name
2207/// (to avoid conflict for example): `use ::std::io::Read as _;`.
2208///
2209/// Using path qualifiers like [`crate`], [`super`] or [`self`] is supported: `use crate::a::b;`.
2210///
2211/// Note that when the wildcard `*` is used on a type, it does not import its methods (though
2212/// for `enum`s it imports the variants, as shown in the example below).
2213///
2214/// ```compile_fail,edition2018
2215/// enum ExampleEnum {
2216/// VariantA,
2217/// VariantB,
2218/// }
2219///
2220/// impl ExampleEnum {
2221/// fn new() -> Self {
2222/// Self::VariantA
2223/// }
2224/// }
2225///
2226/// use ExampleEnum::*;
2227///
2228/// // Compiles.
2229/// let _ = VariantA;
2230///
2231/// // Does not compile!
2232/// let n = new();
2233/// ```
2234///
2235/// For more information on `use` and paths in general, see the [Reference][ref-use-decls].
2236///
2237/// The differences about paths and the `use` keyword between the 2015 and 2018 editions
2238/// can also be found in the [Reference][ref-use-decls].
2239///
2240/// ## Precise capturing
2241///
2242/// The `use<..>` syntax is used within certain `impl Trait` bounds to control which generic
2243/// parameters are captured. This is important for return-position `impl Trait` (RPIT) types,
2244/// as it affects borrow checking by controlling which generic parameters can be used in the
2245/// hidden type.
2246///
2247/// For example, the following function demonstrates an error without precise capturing in
2248/// Rust 2021 and earlier editions:
2249///
2250/// ```rust,compile_fail,edition2021
2251/// fn f(x: &()) -> impl Sized { x }
2252/// ```
2253///
2254/// By using `use<'_>` for precise capturing, it can be resolved:
2255///
2256/// ```rust
2257/// fn f(x: &()) -> impl Sized + use<'_> { x }
2258/// ```
2259///
2260/// This syntax specifies that the elided lifetime be captured and therefore available for
2261/// use in the hidden type.
2262///
2263/// In Rust 2024, opaque types automatically capture all lifetime parameters in scope.
2264/// `use<..>` syntax serves as an important way of opting-out of that default.
2265///
2266/// For more details about precise capturing, see the [Reference][ref-impl-trait].
2267///
2268/// ## Ergonomic clones
2269///
2270/// Use a values, copying its content if the value implements `Copy`, cloning the contents if the
2271/// value implements `UseCloned` or moving it otherwise.
2272///
2273/// [`crate`]: keyword.crate.html
2274/// [`self`]: keyword.self.html
2275/// [`super`]: keyword.super.html
2276/// [ref-use-decls]: ../reference/items/use-declarations.html
2277/// [ref-impl-trait]: ../reference/types/impl-trait.html
2278mod use_keyword {}
2279
2280#[doc(keyword = "where")]
2281//
2282/// Add constraints that must be upheld to use an item.
2283///
2284/// `where` allows specifying constraints on lifetime and generic parameters.
2285/// The [RFC] introducing `where` contains detailed information about the
2286/// keyword.
2287///
2288/// # Examples
2289///
2290/// `where` can be used for constraints with traits:
2291///
2292/// ```rust
2293/// fn new<T: Default>() -> T {
2294/// T::default()
2295/// }
2296///
2297/// fn new_where<T>() -> T
2298/// where
2299/// T: Default,
2300/// {
2301/// T::default()
2302/// }
2303///
2304/// assert_eq!(0.0, new());
2305/// assert_eq!(0.0, new_where());
2306///
2307/// assert_eq!(0, new());
2308/// assert_eq!(0, new_where());
2309/// ```
2310///
2311/// `where` can also be used for lifetimes.
2312///
2313/// This compiles because `longer` outlives `shorter`, thus the constraint is
2314/// respected:
2315///
2316/// ```rust
2317/// fn select<'short, 'long>(s1: &'short str, s2: &'long str, second: bool) -> &'short str
2318/// where
2319/// 'long: 'short,
2320/// {
2321/// if second { s2 } else { s1 }
2322/// }
2323///
2324/// let outer = String::from("Long living ref");
2325/// let longer = &outer;
2326/// {
2327/// let inner = String::from("Short living ref");
2328/// let shorter = &inner;
2329///
2330/// assert_eq!(select(shorter, longer, false), shorter);
2331/// assert_eq!(select(shorter, longer, true), longer);
2332/// }
2333/// ```
2334///
2335/// On the other hand, this will not compile because the `where 'b: 'a` clause
2336/// is missing: the `'b` lifetime is not known to live at least as long as `'a`
2337/// which means this function cannot ensure it always returns a valid reference:
2338///
2339/// ```rust,compile_fail
2340/// fn select<'a, 'b>(s1: &'a str, s2: &'b str, second: bool) -> &'a str
2341/// {
2342/// if second { s2 } else { s1 }
2343/// }
2344/// ```
2345///
2346/// `where` can also be used to express more complicated constraints that cannot
2347/// be written with the `<T: Trait>` syntax:
2348///
2349/// ```rust
2350/// fn first_or_default<I>(mut i: I) -> I::Item
2351/// where
2352/// I: Iterator,
2353/// I::Item: Default,
2354/// {
2355/// i.next().unwrap_or_else(I::Item::default)
2356/// }
2357///
2358/// assert_eq!(first_or_default([1, 2, 3].into_iter()), 1);
2359/// assert_eq!(first_or_default(Vec::<i32>::new().into_iter()), 0);
2360/// ```
2361///
2362/// `where` is available anywhere generic and lifetime parameters are available,
2363/// as can be seen with the [`Cow`](crate::borrow::Cow) type from the standard
2364/// library:
2365///
2366/// ```rust
2367/// # #![allow(dead_code)]
2368/// pub enum Cow<'a, B>
2369/// where
2370/// B: ToOwned + ?Sized,
2371/// {
2372/// Borrowed(&'a B),
2373/// Owned(<B as ToOwned>::Owned),
2374/// }
2375/// ```
2376///
2377/// [RFC]: https://github.com/rust-lang/rfcs/blob/master/text/0135-where.md
2378mod where_keyword {}
2379
2380#[doc(keyword = "while")]
2381//
2382/// Loop while a condition is upheld.
2383///
2384/// A `while` expression is used for predicate loops. The `while` expression runs the conditional
2385/// expression before running the loop body, then runs the loop body if the conditional
2386/// expression evaluates to `true`, or exits the loop otherwise.
2387///
2388/// ```rust
2389/// let mut counter = 0;
2390///
2391/// while counter < 10 {
2392/// println!("{counter}");
2393/// counter += 1;
2394/// }
2395/// ```
2396///
2397/// Like the [`for`] expression, we can use `break` and `continue`. A `while` expression
2398/// cannot break with a value and always evaluates to `()` unlike [`loop`].
2399///
2400/// ```rust
2401/// let mut i = 1;
2402///
2403/// while i < 100 {
2404/// i *= 2;
2405/// if i == 64 {
2406/// break; // Exit when `i` is 64.
2407/// }
2408/// }
2409/// ```
2410///
2411/// As `if` expressions have their pattern matching variant in `if let`, so too do `while`
2412/// expressions with `while let`. The `while let` expression matches the pattern against the
2413/// expression, then runs the loop body if pattern matching succeeds, or exits the loop otherwise.
2414/// We can use `break` and `continue` in `while let` expressions just like in `while`.
2415///
2416/// ```rust
2417/// let mut counter = Some(0);
2418///
2419/// while let Some(i) = counter {
2420/// if i == 10 {
2421/// counter = None;
2422/// } else {
2423/// println!("{i}");
2424/// counter = Some (i + 1);
2425/// }
2426/// }
2427/// ```
2428///
2429/// For more information on `while` and loops in general, see the [reference].
2430///
2431/// See also, [`for`], [`loop`].
2432///
2433/// [`for`]: keyword.for.html
2434/// [`loop`]: keyword.loop.html
2435/// [reference]: ../reference/expressions/loop-expr.html#predicate-loops
2436mod while_keyword {}
2437
2438// 2018 Edition keywords
2439
2440#[doc(alias = "promise")]
2441#[doc(keyword = "async")]
2442//
2443/// Returns a [`Future`] instead of blocking the current thread.
2444///
2445/// Use `async` in front of `fn`, `closure`, or a `block` to turn the marked code into a `Future`.
2446/// As such the code will not be run immediately, but will only be evaluated when the returned
2447/// future is [`.await`]ed.
2448///
2449/// We have written an [async book] detailing `async`/`await` and trade-offs compared to using threads.
2450///
2451/// ## Control Flow
2452/// [`return`] statements and [`?`][try operator] operators within `async` blocks do not cause
2453/// a return from the parent function; rather, they cause the `Future` returned by the block to
2454/// return with that value.
2455///
2456/// For example, the following Rust function will return `5`, causing `x` to take the [`!` type][never type]:
2457/// ```rust
2458/// #[expect(unused_variables)]
2459/// fn example() -> i32 {
2460/// let x = {
2461/// return 5;
2462/// };
2463/// }
2464/// ```
2465/// In contrast, the following asynchronous function assigns a `Future<Output = i32>` to `x`, and
2466/// only returns `5` when `x` is `.await`ed:
2467/// ```rust
2468/// async fn example() -> i32 {
2469/// let x = async {
2470/// return 5;
2471/// };
2472///
2473/// x.await
2474/// }
2475/// ```
2476/// Code using `?` behaves similarly - it causes the `async` block to return a [`Result`] without
2477/// affecting the parent function.
2478///
2479/// Note that you cannot use `break` or `continue` from within an `async` block to affect the
2480/// control flow of a loop in the parent function.
2481///
2482/// Control flow in `async` blocks is documented further in the [async book][async book blocks].
2483///
2484/// ## Editions
2485///
2486/// `async` is a keyword from the 2018 edition onwards.
2487///
2488/// It is available for use in stable Rust from version 1.39 onwards.
2489///
2490/// [`Future`]: future::Future
2491/// [`.await`]: ../std/keyword.await.html
2492/// [async book]: https://rust-lang.github.io/async-book/
2493/// [`return`]: ../std/keyword.return.html
2494/// [try operator]: ../reference/expressions/operator-expr.html#r-expr.try
2495/// [never type]: ../reference/types/never.html
2496/// [`Result`]: result::Result
2497/// [async book blocks]: https://rust-lang.github.io/async-book/part-guide/more-async-await.html#async-blocks
2498mod async_keyword {}
2499
2500#[doc(keyword = "await")]
2501//
2502/// Suspend execution until the result of a [`Future`] is ready.
2503///
2504/// `.await`ing a future will suspend the current function's execution until the executor
2505/// has run the future to completion.
2506///
2507/// Read the [async book] for details on how [`async`]/`await` and executors work.
2508///
2509/// ## Editions
2510///
2511/// `await` is a keyword from the 2018 edition onwards.
2512///
2513/// It is available for use in stable Rust from version 1.39 onwards.
2514///
2515/// [`Future`]: future::Future
2516/// [async book]: https://rust-lang.github.io/async-book/
2517/// [`async`]: ../std/keyword.async.html
2518mod await_keyword {}
2519
2520#[doc(keyword = "dyn")]
2521//
2522/// `dyn` is a prefix of a [trait object]'s type.
2523///
2524/// The `dyn` keyword is used to highlight that calls to methods on the associated `Trait`
2525/// are [dynamically dispatched]. To use the trait this way, it must be *dyn compatible*[^1].
2526///
2527/// Unlike generic parameters or `impl Trait`, the compiler does not know the concrete type that
2528/// is being passed. That is, the type has been [erased].
2529/// As such, a `dyn Trait` reference contains _two_ pointers.
2530/// One pointer goes to the data (e.g., an instance of a struct).
2531/// Another pointer goes to a map of method call names to function pointers
2532/// (known as a virtual method table or vtable).
2533///
2534/// At run-time, when a method needs to be called on the `dyn Trait`, the vtable is consulted to get
2535/// the function pointer and then that function pointer is called.
2536///
2537/// See the Reference for more information on [trait objects][ref-trait-obj]
2538/// and [dyn compatibility][ref-dyn-compat].
2539///
2540/// ## Trade-offs
2541///
2542/// The above indirection is the additional runtime cost of calling a function on a `dyn Trait`.
2543/// Methods called by dynamic dispatch generally cannot be inlined by the compiler.
2544///
2545/// However, `dyn Trait` is likely to produce smaller code than `impl Trait` / generic parameters as
2546/// the method won't be duplicated for each concrete type.
2547///
2548/// [trait object]: ../book/ch17-02-trait-objects.html
2549/// [dynamically dispatched]: https://en.wikipedia.org/wiki/Dynamic_dispatch
2550/// [ref-trait-obj]: ../reference/types/trait-object.html
2551/// [ref-dyn-compat]: ../reference/items/traits.html#dyn-compatibility
2552/// [erased]: https://en.wikipedia.org/wiki/Type_erasure
2553/// [^1]: Formerly known as *object safe*.
2554mod dyn_keyword {}
2555
2556#[doc(keyword = "union")]
2557//
2558/// The [Rust equivalent of a C-style union][union].
2559///
2560/// A `union` looks like a [`struct`] in terms of declaration, but all of its
2561/// fields exist in the same memory, superimposed over one another. For instance,
2562/// if we wanted some bits in memory that we sometimes interpret as a `u32` and
2563/// sometimes as an `f32`, we could write:
2564///
2565/// ```rust
2566/// union IntOrFloat {
2567/// i: u32,
2568/// f: f32,
2569/// }
2570///
2571/// let mut u = IntOrFloat { f: 1.0 };
2572/// // Reading the fields of a union is always unsafe
2573/// assert_eq!(unsafe { u.i }, 1065353216);
2574/// // Updating through any of the field will modify all of them
2575/// u.i = 1073741824;
2576/// assert_eq!(unsafe { u.f }, 2.0);
2577/// ```
2578///
2579/// # Matching on unions
2580///
2581/// It is possible to use pattern matching on `union`s. A single field name must
2582/// be used and it must match the name of one of the `union`'s field.
2583/// Like reading from a `union`, pattern matching on a `union` requires `unsafe`.
2584///
2585/// ```rust
2586/// union IntOrFloat {
2587/// i: u32,
2588/// f: f32,
2589/// }
2590///
2591/// let u = IntOrFloat { f: 1.0 };
2592///
2593/// unsafe {
2594/// match u {
2595/// IntOrFloat { i: 10 } => println!("Found exactly ten!"),
2596/// // Matching the field `f` provides an `f32`.
2597/// IntOrFloat { f } => println!("Found f = {f} !"),
2598/// }
2599/// }
2600/// ```
2601///
2602/// # References to union fields
2603///
2604/// All fields in a `union` are all at the same place in memory which means
2605/// borrowing one borrows the entire `union`, for the same lifetime:
2606///
2607/// ```rust,compile_fail,E0502
2608/// union IntOrFloat {
2609/// i: u32,
2610/// f: f32,
2611/// }
2612///
2613/// let mut u = IntOrFloat { f: 1.0 };
2614///
2615/// let f = unsafe { &u.f };
2616/// // This will not compile because the field has already been borrowed, even
2617/// // if only immutably
2618/// let i = unsafe { &mut u.i };
2619///
2620/// *i = 10;
2621/// println!("f = {f} and i = {i}");
2622/// ```
2623///
2624/// See the [Reference][union] for more information on `union`s.
2625///
2626/// [`struct`]: keyword.struct.html
2627/// [union]: ../reference/items/unions.html
2628mod union_keyword {}