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