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