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