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