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