]> git.lizzy.rs Git - rust.git/blob - library/std/src/keyword_docs.rs
Rollup merge of #75485 - RalfJung:pin, 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 ///
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.
947 ///
948 /// ```rust
949 /// let capture = "hello";
950 /// let closure = move || {
951 ///     println!("rust says {}", capture);
952 /// };
953 /// ```
954 ///
955 /// Note: `move` closures may still implement [`Fn`] or [`FnMut`], even though
956 /// they capture variables by `move`. This is because the traits implemented by
957 /// a closure type are determined by *what* the closure does with captured
958 /// values, not *how* it captures them:
959 ///
960 /// ```rust
961 /// fn create_fn() -> impl Fn() {
962 ///     let text = "Fn".to_owned();
963 ///
964 ///     move || println!("This is a: {}", text)
965 /// }
966 ///
967 ///     let fn_plain = create_fn();
968 ///
969 ///     fn_plain();
970 /// ```
971 ///
972 /// `move` is often used when [threads] are involved.
973 ///
974 /// ```rust
975 /// let x = 5;
976 ///
977 /// std::thread::spawn(move || {
978 ///     println!("captured {} by value", x)
979 /// }).join().unwrap();
980 ///
981 /// // x is no longer available
982 /// ```
983 ///
984 /// `move` is also valid before an async block.
985 ///
986 /// ```rust
987 /// let capture = "hello";
988 /// let block = async move {
989 ///     println!("rust says {} from async block", capture);
990 /// };
991 /// ```
992 ///
993 /// For more information on the `move` keyword, see the [closure]'s section
994 /// of the Rust book or the [threads] section
995 ///
996 /// [`Fn` trait]: ../std/ops/trait.Fn.html
997 /// [closure]: ../book/ch13-01-closures.html
998 /// [threads]: ../book/ch16-01-threads.html#using-move-closures-with-threads
999 mod move_keyword {}
1000
1001 #[doc(keyword = "mut")]
1002 //
1003 /// A mutable variable, reference, or pointer.
1004 ///
1005 /// `mut` can be used in several situations. The first is mutable variables,
1006 /// which can be used anywhere you can bind a value to a variable name. Some
1007 /// examples:
1008 ///
1009 /// ```rust
1010 /// // A mutable variable in the parameter list of a function.
1011 /// fn foo(mut x: u8, y: u8) -> u8 {
1012 ///     x += y;
1013 ///     x
1014 /// }
1015 ///
1016 /// // Modifying a mutable variable.
1017 /// # #[allow(unused_assignments)]
1018 /// let mut a = 5;
1019 /// a = 6;
1020 ///
1021 /// assert_eq!(foo(3, 4), 7);
1022 /// assert_eq!(a, 6);
1023 /// ```
1024 ///
1025 /// The second is mutable references. They can be created from `mut` variables
1026 /// and must be unique: no other variables can have a mutable reference, nor a
1027 /// shared reference.
1028 ///
1029 /// ```rust
1030 /// // Taking a mutable reference.
1031 /// fn push_two(v: &mut Vec<u8>) {
1032 ///     v.push(2);
1033 /// }
1034 ///
1035 /// // A mutable reference cannot be taken to a non-mutable variable.
1036 /// let mut v = vec![0, 1];
1037 /// // Passing a mutable reference.
1038 /// push_two(&mut v);
1039 ///
1040 /// assert_eq!(v, vec![0, 1, 2]);
1041 /// ```
1042 ///
1043 /// ```rust,compile_fail,E0502
1044 /// let mut v = vec![0, 1];
1045 /// let mut_ref_v = &mut v;
1046 /// ##[allow(unused)]
1047 /// let ref_v = &v;
1048 /// mut_ref_v.push(2);
1049 /// ```
1050 ///
1051 /// Mutable raw pointers work much like mutable references, with the added
1052 /// possibility of not pointing to a valid object. The syntax is `*mut Type`.
1053 ///
1054 /// More information on mutable references and pointers can be found in```
1055 /// [Reference].
1056 ///
1057 /// [Reference]: ../reference/types/pointer.html#mutable-references-mut
1058 mod mut_keyword {}
1059
1060 #[doc(keyword = "pub")]
1061 //
1062 /// Make an item visible to others.
1063 ///
1064 /// The keyword `pub` makes any module, function, or data structure accessible from inside
1065 /// of external modules. The `pub` keyword may also be used in a `use` declaration to re-export
1066 /// an identifier from a namespace.
1067 ///
1068 /// For more information on the `pub` keyword, please see the visibility section
1069 /// of the [reference] and for some examples, see [Rust by Example].
1070 ///
1071 /// [reference]:../reference/visibility-and-privacy.html?highlight=pub#visibility-and-privacy
1072 /// [Rust by Example]:../rust-by-example/mod/visibility.html
1073 mod pub_keyword {}
1074
1075 #[doc(keyword = "ref")]
1076 //
1077 /// Bind by reference during pattern matching.
1078 ///
1079 /// `ref` annotates pattern bindings to make them borrow rather than move.
1080 /// It is **not** a part of the pattern as far as matching is concerned: it does
1081 /// not affect *whether* a value is matched, only *how* it is matched.
1082 ///
1083 /// By default, [`match`] statements consume all they can, which can sometimes
1084 /// be a problem, when you don't really need the value to be moved and owned:
1085 ///
1086 /// ```compile_fail,E0382
1087 /// let maybe_name = Some(String::from("Alice"));
1088 /// // The variable 'maybe_name' is consumed here ...
1089 /// match maybe_name {
1090 ///     Some(n) => println!("Hello, {}", n),
1091 ///     _ => println!("Hello, world"),
1092 /// }
1093 /// // ... and is now unavailable.
1094 /// println!("Hello again, {}", maybe_name.unwrap_or("world".into()));
1095 /// ```
1096 ///
1097 /// Using the `ref` keyword, the value is only borrowed, not moved, making it
1098 /// available for use after the [`match`] statement:
1099 ///
1100 /// ```
1101 /// let maybe_name = Some(String::from("Alice"));
1102 /// // Using `ref`, the value is borrowed, not moved ...
1103 /// match maybe_name {
1104 ///     Some(ref n) => println!("Hello, {}", n),
1105 ///     _ => println!("Hello, world"),
1106 /// }
1107 /// // ... so it's available here!
1108 /// println!("Hello again, {}", maybe_name.unwrap_or("world".into()));
1109 /// ```
1110 ///
1111 /// # `&` vs `ref`
1112 ///
1113 /// - `&` denotes that your pattern expects a reference to an object. Hence `&`
1114 /// is a part of said pattern: `&Foo` matches different objects than `Foo` does.
1115 ///
1116 /// - `ref` indicates that you want a reference to an unpacked value. It is not
1117 /// matched against: `Foo(ref foo)` matches the same objects as `Foo(foo)`.
1118 ///
1119 /// See also the [Reference] for more information.
1120 ///
1121 /// [`match`]: keyword.match.html
1122 /// [Reference]: ../reference/patterns.html#identifier-patterns
1123 mod ref_keyword {}
1124
1125 #[doc(keyword = "return")]
1126 //
1127 /// Return a value from a function.
1128 ///
1129 /// A `return` marks the end of an execution path in a function:
1130 ///
1131 /// ```
1132 /// fn foo() -> i32 {
1133 ///     return 3;
1134 /// }
1135 /// assert_eq!(foo(), 3);
1136 /// ```
1137 ///
1138 /// `return` is not needed when the returned value is the last expression in the
1139 /// function. In this case the `;` is omitted:
1140 ///
1141 /// ```
1142 /// fn foo() -> i32 {
1143 ///     3
1144 /// }
1145 /// assert_eq!(foo(), 3);
1146 /// ```
1147 ///
1148 /// `return` returns from the function immediately (an "early return"):
1149 ///
1150 /// ```no_run
1151 /// use std::fs::File;
1152 /// use std::io::{Error, ErrorKind, Read, Result};
1153 ///
1154 /// fn main() -> Result<()> {
1155 ///     let mut file = match File::open("foo.txt") {
1156 ///         Ok(f) => f,
1157 ///         Err(e) => return Err(e),
1158 ///     };
1159 ///
1160 ///     let mut contents = String::new();
1161 ///     let size = match file.read_to_string(&mut contents) {
1162 ///         Ok(s) => s,
1163 ///         Err(e) => return Err(e),
1164 ///     };
1165 ///
1166 ///     if contents.contains("impossible!") {
1167 ///         return Err(Error::new(ErrorKind::Other, "oh no!"));
1168 ///     }
1169 ///
1170 ///     if size > 9000 {
1171 ///         return Err(Error::new(ErrorKind::Other, "over 9000!"));
1172 ///     }
1173 ///
1174 ///     assert_eq!(contents, "Hello, world!");
1175 ///     Ok(())
1176 /// }
1177 /// ```
1178 mod return_keyword {}
1179
1180 #[doc(keyword = "self")]
1181 //
1182 /// The receiver of a method, or the current module.
1183 ///
1184 /// `self` is used in two situations: referencing the current module and marking
1185 /// the receiver of a method.
1186 ///
1187 /// In paths, `self` can be used to refer to the current module, either in a
1188 /// [`use`] statement or in a path to access an element:
1189 ///
1190 /// ```
1191 /// # #![allow(unused_imports)]
1192 /// use std::io::{self, Read};
1193 /// ```
1194 ///
1195 /// Is functionally the same as:
1196 ///
1197 /// ```
1198 /// # #![allow(unused_imports)]
1199 /// use std::io;
1200 /// use std::io::Read;
1201 /// ```
1202 ///
1203 /// Using `self` to access an element in the current module:
1204 ///
1205 /// ```
1206 /// # #![allow(dead_code)]
1207 /// # fn main() {}
1208 /// fn foo() {}
1209 /// fn bar() {
1210 ///     self::foo()
1211 /// }
1212 /// ```
1213 ///
1214 /// `self` as the current receiver for a method allows to omit the parameter
1215 /// type most of the time. With the exception of this particularity, `self` is
1216 /// used much like any other parameter:
1217 ///
1218 /// ```
1219 /// struct Foo(i32);
1220 ///
1221 /// impl Foo {
1222 ///     // No `self`.
1223 ///     fn new() -> Self {
1224 ///         Self(0)
1225 ///     }
1226 ///
1227 ///     // Consuming `self`.
1228 ///     fn consume(self) -> Self {
1229 ///         Self(self.0 + 1)
1230 ///     }
1231 ///
1232 ///     // Borrowing `self`.
1233 ///     fn borrow(&self) -> &i32 {
1234 ///         &self.0
1235 ///     }
1236 ///
1237 ///     // Borrowing `self` mutably.
1238 ///     fn borrow_mut(&mut self) -> &mut i32 {
1239 ///         &mut self.0
1240 ///     }
1241 /// }
1242 ///
1243 /// // This method must be called with a `Type::` prefix.
1244 /// let foo = Foo::new();
1245 /// assert_eq!(foo.0, 0);
1246 ///
1247 /// // Those two calls produces the same result.
1248 /// let foo = Foo::consume(foo);
1249 /// assert_eq!(foo.0, 1);
1250 /// let foo = foo.consume();
1251 /// assert_eq!(foo.0, 2);
1252 ///
1253 /// // Borrowing is handled automatically with the second syntax.
1254 /// let borrow_1 = Foo::borrow(&foo);
1255 /// let borrow_2 = foo.borrow();
1256 /// assert_eq!(borrow_1, borrow_2);
1257 ///
1258 /// // Borrowing mutably is handled automatically too with the second syntax.
1259 /// let mut foo = Foo::new();
1260 /// *Foo::borrow_mut(&mut foo) += 1;
1261 /// assert_eq!(foo.0, 1);
1262 /// *foo.borrow_mut() += 1;
1263 /// assert_eq!(foo.0, 2);
1264 /// ```
1265 ///
1266 /// Note that this automatic conversion when calling `foo.method()` is not
1267 /// limited to the examples above. See the [Reference] for more information.
1268 ///
1269 /// [`use`]: keyword.use.html
1270 /// [Reference]: ../reference/items/associated-items.html#methods
1271 mod self_keyword {}
1272
1273 #[doc(keyword = "Self")]
1274 //
1275 /// The implementing type within a [`trait`] or [`impl`] block, or the current type within a type
1276 /// definition.
1277 ///
1278 /// Within a type definition:
1279 ///
1280 /// ```
1281 /// # #![allow(dead_code)]
1282 /// struct Node {
1283 ///     elem: i32,
1284 ///     // `Self` is a `Node` here.
1285 ///     next: Option<Box<Self>>,
1286 /// }
1287 /// ```
1288 ///
1289 /// In an [`impl`] block:
1290 ///
1291 /// ```
1292 /// struct Foo(i32);
1293 ///
1294 /// impl Foo {
1295 ///     fn new() -> Self {
1296 ///         Self(0)
1297 ///     }
1298 /// }
1299 ///
1300 /// assert_eq!(Foo::new().0, Foo(0).0);
1301 /// ```
1302 ///
1303 /// Generic parameters are implicit with `Self`:
1304 ///
1305 /// ```
1306 /// # #![allow(dead_code)]
1307 /// struct Wrap<T> {
1308 ///     elem: T,
1309 /// }
1310 ///
1311 /// impl<T> Wrap<T> {
1312 ///     fn new(elem: T) -> Self {
1313 ///         Self { elem }
1314 ///     }
1315 /// }
1316 /// ```
1317 ///
1318 /// In a [`trait`] definition and related [`impl`] block:
1319 ///
1320 /// ```
1321 /// trait Example {
1322 ///     fn example() -> Self;
1323 /// }
1324 ///
1325 /// struct Foo(i32);
1326 ///
1327 /// impl Example for Foo {
1328 ///     fn example() -> Self {
1329 ///         Self(42)
1330 ///     }
1331 /// }
1332 ///
1333 /// assert_eq!(Foo::example().0, Foo(42).0);
1334 /// ```
1335 ///
1336 /// [`impl`]: keyword.impl.html
1337 /// [`trait`]: keyword.trait.html
1338 mod self_upper_keyword {}
1339
1340 #[doc(keyword = "static")]
1341 //
1342 /// A static item is a value which is valid for the entire duration of your
1343 /// program (a `'static` lifetime).
1344 ///
1345 /// On the surface, `static` items seem very similar to [`const`]s: both contain
1346 /// a value, both require type annotations and both can only be initialized with
1347 /// constant functions and values. However, `static`s are notably different in
1348 /// that they represent a location in memory. That means that you can have
1349 /// references to `static` items and potentially even modify them, making them
1350 /// essentially global variables.
1351 ///
1352 /// Static items do not call [`drop`] at the end of the program.
1353 ///
1354 /// There are two types of `static` items: those declared in association with
1355 /// the [`mut`] keyword and those without.
1356 ///
1357 /// Static items cannot be moved:
1358 ///
1359 /// ```rust,compile_fail,E0507
1360 /// static VEC: Vec<u32> = vec![];
1361 ///
1362 /// fn move_vec(v: Vec<u32>) -> Vec<u32> {
1363 ///     v
1364 /// }
1365 ///
1366 /// // This line causes an error
1367 /// move_vec(VEC);
1368 /// ```
1369 ///
1370 /// # Simple `static`s
1371 ///
1372 /// Accessing non-[`mut`] `static` items is considered safe, but some
1373 /// restrictions apply. Most notably, the type of a `static` value needs to
1374 /// implement the [`Sync`] trait, ruling out interior mutability containers
1375 /// like [`RefCell`]. See the [Reference] for more information.
1376 ///
1377 /// ```rust
1378 /// static FOO: [i32; 5] = [1, 2, 3, 4, 5];
1379 ///
1380 /// let r1 = &FOO as *const _;
1381 /// let r2 = &FOO as *const _;
1382 /// // With a strictly read-only static, references will have the same address
1383 /// assert_eq!(r1, r2);
1384 /// // A static item can be used just like a variable in many cases
1385 /// println!("{:?}", FOO);
1386 /// ```
1387 ///
1388 /// # Mutable `static`s
1389 ///
1390 /// If a `static` item is declared with the [`mut`] keyword, then it is allowed
1391 /// to be modified by the program. However, accessing mutable `static`s can
1392 /// cause undefined behavior in a number of ways, for example due to data races
1393 /// in a multithreaded context. As such, all accesses to mutable `static`s
1394 /// require an [`unsafe`] block.
1395 ///
1396 /// Despite their unsafety, mutable `static`s are necessary in many contexts:
1397 /// they can be used to represent global state shared by the whole program or in
1398 /// [`extern`] blocks to bind to variables from C libraries.
1399 ///
1400 /// In an [`extern`] block:
1401 ///
1402 /// ```rust,no_run
1403 /// # #![allow(dead_code)]
1404 /// extern "C" {
1405 ///     static mut ERROR_MESSAGE: *mut std::os::raw::c_char;
1406 /// }
1407 /// ```
1408 ///
1409 /// Mutable `static`s, just like simple `static`s, have some restrictions that
1410 /// apply to them. See the [Reference] for more information.
1411 ///
1412 /// [`const`]: keyword.const.html
1413 /// [`extern`]: keyword.extern.html
1414 /// [`mut`]: keyword.mut.html
1415 /// [`unsafe`]: keyword.unsafe.html
1416 /// [`drop`]: mem/fn.drop.html
1417 /// [`Sync`]: marker/trait.Sync.html
1418 /// [`RefCell`]: cell/struct.RefCell.html
1419 /// [Reference]: ../reference/items/static-items.html
1420 mod static_keyword {}
1421
1422 #[doc(keyword = "struct")]
1423 //
1424 /// A type that is composed of other types.
1425 ///
1426 /// Structs in Rust come in three flavors: Structs with named fields, tuple structs, and unit
1427 /// structs.
1428 ///
1429 /// ```rust
1430 /// struct Regular {
1431 ///     field1: f32,
1432 ///     field2: String,
1433 ///     pub field3: bool
1434 /// }
1435 ///
1436 /// struct Tuple(u32, String);
1437 ///
1438 /// struct Unit;
1439 /// ```
1440 ///
1441 /// Regular structs are the most commonly used. Each field defined within them has a name and a
1442 /// type, and once defined can be accessed using `example_struct.field` syntax. The fields of a
1443 /// struct share its mutability, so `foo.bar = 2;` would only be valid if `foo` was mutable. Adding
1444 /// `pub` to a field makes it visible to code in other modules, as well as allowing it to be
1445 /// directly accessed and modified.
1446 ///
1447 /// Tuple structs are similar to regular structs, but its fields have no names. They are used like
1448 /// tuples, with deconstruction possible via `let TupleStruct(x, y) = foo;` syntax. For accessing
1449 /// individual variables, the same syntax is used as with regular tuples, namely `foo.0`, `foo.1`,
1450 /// etc, starting at zero.
1451 ///
1452 /// Unit structs are most commonly used as marker. They have a size of zero bytes, but unlike empty
1453 /// enums they can be instantiated, making them isomorphic to the unit type `()`. Unit structs are
1454 /// useful when you need to implement a trait on something, but don't need to store any data inside
1455 /// it.
1456 ///
1457 /// # Instantiation
1458 ///
1459 /// Structs can be instantiated in different ways, all of which can be mixed and
1460 /// matched as needed. The most common way to make a new struct is via a constructor method such as
1461 /// `new()`, but when that isn't available (or you're writing the constructor itself), struct
1462 /// literal syntax is used:
1463 ///
1464 /// ```rust
1465 /// # struct Foo { field1: f32, field2: String, etc: bool }
1466 /// let example = Foo {
1467 ///     field1: 42.0,
1468 ///     field2: "blah".to_string(),
1469 ///     etc: true,
1470 /// };
1471 /// ```
1472 ///
1473 /// It's only possible to directly instantiate a struct using struct literal syntax when all of its
1474 /// fields are visible to you.
1475 ///
1476 /// There are a handful of shortcuts provided to make writing constructors more convenient, most
1477 /// common of which is the Field Init shorthand. When there is a variable and a field of the same
1478 /// name, the assignment can be simplified from `field: field` into simply `field`. The following
1479 /// example of a hypothetical constructor demonstrates this:
1480 ///
1481 /// ```rust
1482 /// struct User {
1483 ///     name: String,
1484 ///     admin: bool,
1485 /// }
1486 ///
1487 /// impl User {
1488 ///     pub fn new(name: String) -> Self {
1489 ///         Self {
1490 ///             name,
1491 ///             admin: false,
1492 ///         }
1493 ///     }
1494 /// }
1495 /// ```
1496 ///
1497 /// Another shortcut for struct instantiation is available, used when you need to make a new
1498 /// struct that has the same values as most of a previous struct of the same type, called struct
1499 /// update syntax:
1500 ///
1501 /// ```rust
1502 /// # struct Foo { field1: String, field2: () }
1503 /// # let thing = Foo { field1: "".to_string(), field2: () };
1504 /// let updated_thing = Foo {
1505 ///     field1: "a new value".to_string(),
1506 ///     ..thing
1507 /// };
1508 /// ```
1509 ///
1510 /// Tuple structs are instantiated in the same way as tuples themselves, except with the struct's
1511 /// name as a prefix: `Foo(123, false, 0.1)`.
1512 ///
1513 /// Empty structs are instantiated with just their name, and don't need anything else. `let thing =
1514 /// EmptyStruct;`
1515 ///
1516 /// # Style conventions
1517 ///
1518 /// Structs are always written in CamelCase, with few exceptions. While the trailing comma on a
1519 /// struct's list of fields can be omitted, it's usually kept for convenience in adding and
1520 /// removing fields down the line.
1521 ///
1522 /// For more information on structs, take a look at the [Rust Book][book] or the
1523 /// [Reference][reference].
1524 ///
1525 /// [`PhantomData`]: marker/struct.PhantomData.html
1526 /// [book]: ../book/ch05-01-defining-structs.html
1527 /// [reference]: ../reference/items/structs.html
1528 mod struct_keyword {}
1529
1530 #[doc(keyword = "super")]
1531 //
1532 /// The parent of the current [module].
1533 ///
1534 /// ```rust
1535 /// # #![allow(dead_code)]
1536 /// # fn main() {}
1537 /// mod a {
1538 ///     pub fn foo() {}
1539 /// }
1540 /// mod b {
1541 ///     pub fn foo() {
1542 ///         super::a::foo(); // call a's foo function
1543 ///     }
1544 /// }
1545 /// ```
1546 ///
1547 /// It is also possible to use `super` multiple times: `super::super::foo`,
1548 /// going up the ancestor chain.
1549 ///
1550 /// See the [Reference] for more information.
1551 ///
1552 /// [module]: ../reference/items/modules.html
1553 /// [Reference]: ../reference/paths.html#super
1554 mod super_keyword {}
1555
1556 #[doc(keyword = "trait")]
1557 //
1558 /// A common interface for a group of types.
1559 ///
1560 /// A `trait` is like an interface that data types can implement. When a type
1561 /// implements a trait it can be treated abstractly as that trait using generics
1562 /// or trait objects.
1563 ///
1564 /// Traits can be made up of three varieties of associated items:
1565 ///
1566 /// - functions and methods
1567 /// - types
1568 /// - constants
1569 ///
1570 /// Traits may also contain additional type parameters. Those type parameters
1571 /// or the trait itself can be constrained by other traits.
1572 ///
1573 /// Traits can serve as markers or carry other logical semantics that
1574 /// aren't expressed through their items. When a type implements that
1575 /// trait it is promising to uphold its contract. [`Send`] and [`Sync`] are two
1576 /// such marker traits present in the standard library.
1577 ///
1578 /// See the [Reference][Ref-Traits] for a lot more information on traits.
1579 ///
1580 /// # Examples
1581 ///
1582 /// Traits are declared using the `trait` keyword. Types can implement them
1583 /// using [`impl`] `Trait` [`for`] `Type`:
1584 ///
1585 /// ```rust
1586 /// trait Zero {
1587 ///     const ZERO: Self;
1588 ///     fn is_zero(&self) -> bool;
1589 /// }
1590 ///
1591 /// impl Zero for i32 {
1592 ///     const ZERO: Self = 0;
1593 ///
1594 ///     fn is_zero(&self) -> bool {
1595 ///         *self == Self::ZERO
1596 ///     }
1597 /// }
1598 ///
1599 /// assert_eq!(i32::ZERO, 0);
1600 /// assert!(i32::ZERO.is_zero());
1601 /// assert!(!4.is_zero());
1602 /// ```
1603 ///
1604 /// With an associated type:
1605 ///
1606 /// ```rust
1607 /// trait Builder {
1608 ///     type Built;
1609 ///
1610 ///     fn build(&self) -> Self::Built;
1611 /// }
1612 /// ```
1613 ///
1614 /// Traits can be generic, with constraints or without:
1615 ///
1616 /// ```rust
1617 /// trait MaybeFrom<T> {
1618 ///     fn maybe_from(value: T) -> Option<Self>
1619 ///     where
1620 ///         Self: Sized;
1621 /// }
1622 /// ```
1623 ///
1624 /// Traits can build upon the requirements of other traits. In the example
1625 /// below `Iterator` is a **supertrait** and `ThreeIterator` is a **subtrait**:
1626 ///
1627 /// ```rust
1628 /// trait ThreeIterator: std::iter::Iterator {
1629 ///     fn next_three(&mut self) -> Option<[Self::Item; 3]>;
1630 /// }
1631 /// ```
1632 ///
1633 /// Traits can be used in functions, as parameters:
1634 ///
1635 /// ```rust
1636 /// # #![allow(dead_code)]
1637 /// fn debug_iter<I: Iterator>(it: I) where I::Item: std::fmt::Debug {
1638 ///     for elem in it {
1639 ///         println!("{:#?}", elem);
1640 ///     }
1641 /// }
1642 ///
1643 /// // u8_len_1, u8_len_2 and u8_len_3 are equivalent
1644 ///
1645 /// fn u8_len_1(val: impl Into<Vec<u8>>) -> usize {
1646 ///     val.into().len()
1647 /// }
1648 ///
1649 /// fn u8_len_2<T: Into<Vec<u8>>>(val: T) -> usize {
1650 ///     val.into().len()
1651 /// }
1652 ///
1653 /// fn u8_len_3<T>(val: T) -> usize
1654 /// where
1655 ///     T: Into<Vec<u8>>,
1656 /// {
1657 ///     val.into().len()
1658 /// }
1659 /// ```
1660 ///
1661 /// Or as return types:
1662 ///
1663 /// ```rust
1664 /// # #![allow(dead_code)]
1665 /// fn from_zero_to(v: u8) -> impl Iterator<Item = u8> {
1666 ///     (0..v).into_iter()
1667 /// }
1668 /// ```
1669 ///
1670 /// The use of the [`impl`] keyword in this position allows the function writer
1671 /// to hide the concrete type as an implementation detail which can change
1672 /// without breaking user's code.
1673 ///
1674 /// # Trait objects
1675 ///
1676 /// A *trait object* is an opaque value of another type that implements a set of
1677 /// traits. A trait object implements all specified traits as well as their
1678 /// supertraits (if any).
1679 ///
1680 /// The syntax is the following: `dyn BaseTrait + AutoTrait1 + ... AutoTraitN`.
1681 /// Only one `BaseTrait` can be used so this will not compile:
1682 ///
1683 /// ```rust,compile_fail,E0225
1684 /// trait A {}
1685 /// trait B {}
1686 ///
1687 /// let _: Box<dyn A + B>;
1688 /// ```
1689 ///
1690 /// Neither will this, which is a syntax error:
1691 ///
1692 /// ```rust,compile_fail
1693 /// trait A {}
1694 /// trait B {}
1695 ///
1696 /// let _: Box<dyn A + dyn B>;
1697 /// ```
1698 ///
1699 /// On the other hand, this is correct:
1700 ///
1701 /// ```rust
1702 /// trait A {}
1703 ///
1704 /// let _: Box<dyn A + Send + Sync>;
1705 /// ```
1706 ///
1707 /// The [Reference][Ref-Trait-Objects] has more information about trait objects,
1708 /// their limitations and the differences between editions.
1709 ///
1710 /// # Unsafe traits
1711 ///
1712 /// Some traits may be unsafe to implement. Using the [`unsafe`] keyword in
1713 /// front of the trait's declaration is used to mark this:
1714 ///
1715 /// ```rust
1716 /// unsafe trait UnsafeTrait {}
1717 ///
1718 /// unsafe impl UnsafeTrait for i32 {}
1719 /// ```
1720 ///
1721 /// # Differences between the 2015 and 2018 editions
1722 ///
1723 /// In the 2015 edition parameters pattern where not needed for traits:
1724 ///
1725 /// ```rust,edition2015
1726 /// trait Tr {
1727 ///     fn f(i32);
1728 /// }
1729 /// ```
1730 ///
1731 /// This behavior is no longer valid in edition 2018.
1732 ///
1733 /// [`for`]: keyword.for.html
1734 /// [`impl`]: keyword.impl.html
1735 /// [`unsafe`]: keyword.unsafe.html
1736 /// [`Send`]: marker/trait.Send.html
1737 /// [`Sync`]: marker/trait.Sync.html
1738 /// [Ref-Traits]: ../reference/items/traits.html
1739 /// [Ref-Trait-Objects]: ../reference/types/trait-object.html
1740 mod trait_keyword {}
1741
1742 #[doc(keyword = "true")]
1743 //
1744 /// A value of type [`bool`] representing logical **true**.
1745 ///
1746 /// Logically `true` is not equal to [`false`].
1747 ///
1748 /// ## Control structures that check for **true**
1749 ///
1750 /// Several of Rust's control structures will check for a `bool` condition evaluating to **true**.
1751 ///
1752 ///   * The condition in an [`if`] expression must be of type `bool`.
1753 ///     Whenever that condition evaluates to **true**, the `if` expression takes
1754 ///     on the value of the first block. If however, the condition evaluates
1755 ///     to `false`, the expression takes on value of the `else` block if there is one.
1756 ///
1757 ///   * [`while`] is another control flow construct expecting a `bool`-typed condition.
1758 ///     As long as the condition evaluates to **true**, the `while` loop will continually
1759 ///     evaluate its associated block.
1760 ///
1761 ///   * [`match`] arms can have guard clauses on them.
1762 ///
1763 /// [`if`]: keyword.if.html
1764 /// [`while`]: keyword.while.html
1765 /// [`match`]: ../reference/expressions/match-expr.html#match-guards
1766 /// [`false`]: keyword.false.html
1767 /// [`bool`]: primitive.bool.html
1768 mod true_keyword {}
1769
1770 #[doc(keyword = "type")]
1771 //
1772 /// Define an alias for an existing type.
1773 ///
1774 /// The syntax is `type Name = ExistingType;`.
1775 ///
1776 /// # Examples
1777 ///
1778 /// `type` does **not** create a new type:
1779 ///
1780 /// ```rust
1781 /// type Meters = u32;
1782 /// type Kilograms = u32;
1783 ///
1784 /// let m: Meters = 3;
1785 /// let k: Kilograms = 3;
1786 ///
1787 /// assert_eq!(m, k);
1788 /// ```
1789 ///
1790 /// In traits, `type` is used to declare an [associated type]:
1791 ///
1792 /// ```rust
1793 /// trait Iterator {
1794 ///     // associated type declaration
1795 ///     type Item;
1796 ///     fn next(&mut self) -> Option<Self::Item>;
1797 /// }
1798 ///
1799 /// struct Once<T>(Option<T>);
1800 ///
1801 /// impl<T> Iterator for Once<T> {
1802 ///     // associated type definition
1803 ///     type Item = T;
1804 ///     fn next(&mut self) -> Option<Self::Item> {
1805 ///         self.0.take()
1806 ///     }
1807 /// }
1808 /// ```
1809 ///
1810 /// [`trait`]: keyword.trait.html
1811 /// [associated type]: ../reference/items/associated-items.html#associated-types
1812 mod type_keyword {}
1813
1814 #[doc(keyword = "unsafe")]
1815 //
1816 /// Code or interfaces whose [memory safety] cannot be verified by the type
1817 /// system.
1818 ///
1819 /// The `unsafe` keyword has two uses: to declare the existence of contracts the
1820 /// compiler can't check (`unsafe fn` and `unsafe trait`), and to declare that a
1821 /// programmer has checked that these contracts have been upheld (`unsafe {}`
1822 /// and `unsafe impl`, but also `unsafe fn` -- see below). They are not mutually
1823 /// exclusive, as can be seen in `unsafe fn`.
1824 ///
1825 /// # Unsafe abilities
1826 ///
1827 /// **No matter what, Safe Rust can't cause Undefined Behavior**. This is
1828 /// referred to as [soundness]: a well-typed program actually has the desired
1829 /// properties. The [Nomicon][nomicon-soundness] has a more detailed explanation
1830 /// on the subject.
1831 ///
1832 /// To ensure soundness, Safe Rust is restricted enough that it can be
1833 /// automatically checked. Sometimes, however, it is necessary to write code
1834 /// that is correct for reasons which are too clever for the compiler to
1835 /// understand. In those cases, you need to use Unsafe Rust.
1836 ///
1837 /// Here are the abilities Unsafe Rust has in addition to Safe Rust:
1838 ///
1839 /// - Dereference [raw pointers]
1840 /// - Implement `unsafe` [`trait`]s
1841 /// - Call `unsafe` functions
1842 /// - Mutate [`static`]s (including [`extern`]al ones)
1843 /// - Access fields of [`union`]s
1844 ///
1845 /// However, this extra power comes with extra responsibilities: it is now up to
1846 /// you to ensure soundness. The `unsafe` keyword helps by clearly marking the
1847 /// pieces of code that need to worry about this.
1848 ///
1849 /// ## The different meanings of `unsafe`
1850 ///
1851 /// Not all uses of `unsafe` are equivalent: some are here to mark the existence
1852 /// of a contract the programmer must check, others are to say "I have checked
1853 /// the contract, go ahead and do this". The following
1854 /// [discussion on Rust Internals] has more in-depth explanations about this but
1855 /// here is a summary of the main points:
1856 ///
1857 /// - `unsafe fn`: calling this function means abiding by a contract the
1858 /// compiler cannot enforce.
1859 /// - `unsafe trait`: implementing the [`trait`] means abiding by a
1860 /// contract the compiler cannot enforce.
1861 /// - `unsafe {}`: the contract necessary to call the operations inside the
1862 /// block has been checked by the programmer and is guaranteed to be respected.
1863 /// - `unsafe impl`: the contract necessary to implement the trait has been
1864 /// checked by the programmer and is guaranteed to be respected.
1865 ///
1866 /// `unsafe fn` also acts like an `unsafe {}` block
1867 /// around the code inside the function. This means it is not just a signal to
1868 /// the caller, but also promises that the preconditions for the operations
1869 /// inside the function are upheld. Mixing these two meanings can be confusing
1870 /// and [proposal]s exist to use `unsafe {}` blocks inside such functions when
1871 /// making `unsafe` operations.
1872 ///
1873 /// See the [Rustnomicon] and the [Reference] for more informations.
1874 ///
1875 /// # Examples
1876 ///
1877 /// ## Marking elements as `unsafe`
1878 ///
1879 /// `unsafe` can be used on functions. Note that functions and statics declared
1880 /// in [`extern`] blocks are implicitly marked as `unsafe` (but not functions
1881 /// declared as `extern "something" fn ...`). Mutable statics are always unsafe,
1882 /// wherever they are declared. Methods can also be declared as `unsafe`:
1883 ///
1884 /// ```rust
1885 /// # #![allow(dead_code)]
1886 /// static mut FOO: &str = "hello";
1887 ///
1888 /// unsafe fn unsafe_fn() {}
1889 ///
1890 /// extern "C" {
1891 ///     fn unsafe_extern_fn();
1892 ///     static BAR: *mut u32;
1893 /// }
1894 ///
1895 /// trait SafeTraitWithUnsafeMethod {
1896 ///     unsafe fn unsafe_method(&self);
1897 /// }
1898 ///
1899 /// struct S;
1900 ///
1901 /// impl S {
1902 ///     unsafe fn unsafe_method_on_struct() {}
1903 /// }
1904 /// ```
1905 ///
1906 /// Traits can also be declared as `unsafe`:
1907 ///
1908 /// ```rust
1909 /// unsafe trait UnsafeTrait {}
1910 /// ```
1911 ///
1912 /// Since `unsafe fn` and `unsafe trait` indicate that there is a safety
1913 /// contract that the compiler cannot enforce, documenting it is important. The
1914 /// standard library has many examples of this, like the following which is an
1915 /// extract from [`Vec::set_len`]. The `# Safety` section explains the contract
1916 /// that must be fulfilled to safely call the function.
1917 ///
1918 /// ```rust,ignore (stub-to-show-doc-example)
1919 /// /// Forces the length of the vector to `new_len`.
1920 /// ///
1921 /// /// This is a low-level operation that maintains none of the normal
1922 /// /// invariants of the type. Normally changing the length of a vector
1923 /// /// is done using one of the safe operations instead, such as
1924 /// /// `truncate`, `resize`, `extend`, or `clear`.
1925 /// ///
1926 /// /// # Safety
1927 /// ///
1928 /// /// - `new_len` must be less than or equal to `capacity()`.
1929 /// /// - The elements at `old_len..new_len` must be initialized.
1930 /// pub unsafe fn set_len(&mut self, new_len: usize)
1931 /// ```
1932 ///
1933 /// ## Using `unsafe {}` blocks and `impl`s
1934 ///
1935 /// Performing `unsafe` operations requires an `unsafe {}` block:
1936 ///
1937 /// ```rust
1938 /// # #![allow(dead_code)]
1939 /// /// Dereference the given pointer.
1940 /// ///
1941 /// /// # Safety
1942 /// ///
1943 /// /// `ptr` must be aligned and must not be dangling.
1944 /// unsafe fn deref_unchecked(ptr: *const i32) -> i32 {
1945 ///     *ptr
1946 /// }
1947 ///
1948 /// let a = 3;
1949 /// let b = &a as *const _;
1950 /// // SAFETY: `a` has not been dropped and references are always aligned,
1951 /// // so `b` is a valid address.
1952 /// unsafe { assert_eq!(*b, deref_unchecked(b)); };
1953 /// ```
1954 ///
1955 /// Traits marked as `unsafe` must be [`impl`]emented using `unsafe impl`. This
1956 /// makes a guarantee to other `unsafe` code that the implementation satisfies
1957 /// the trait's safety contract. The [Send] and [Sync] traits are examples of
1958 /// this behaviour in the standard library.
1959 ///
1960 /// ```rust
1961 /// /// Implementors of this trait must guarantee an element is always
1962 /// /// accessible with index 3.
1963 /// unsafe trait ThreeIndexable<T> {
1964 ///     /// Returns a reference to the element with index 3 in `&self`.
1965 ///     fn three(&self) -> &T;
1966 /// }
1967 ///
1968 /// // The implementation of `ThreeIndexable` for `[T; 4]` is `unsafe`
1969 /// // because the implementor must abide by a contract the compiler cannot
1970 /// // check but as a programmer we know there will always be a valid element
1971 /// // at index 3 to access.
1972 /// unsafe impl<T> ThreeIndexable<T> for [T; 4] {
1973 ///     fn three(&self) -> &T {
1974 ///         // SAFETY: implementing the trait means there always is an element
1975 ///         // with index 3 accessible.
1976 ///         unsafe { self.get_unchecked(3) }
1977 ///     }
1978 /// }
1979 ///
1980 /// let a = [1, 2, 4, 8];
1981 /// assert_eq!(a.three(), &8);
1982 /// ```
1983 ///
1984 /// [`extern`]: keyword.extern.html
1985 /// [`trait`]: keyword.trait.html
1986 /// [`static`]: keyword.static.html
1987 /// [`union`]: keyword.union.html
1988 /// [`impl`]: keyword.impl.html
1989 /// [Send]: marker/trait.Send.html
1990 /// [Sync]: marker/trait.Sync.html
1991 /// [`Vec::set_len`]: vec/struct.Vec.html#method.set_len
1992 /// [raw pointers]: ../reference/types/pointer.html
1993 /// [memory safety]: ../book/ch19-01-unsafe-rust.html
1994 /// [Rustnomicon]: ../nomicon/index.html
1995 /// [nomicon-soundness]: ../nomicon/safe-unsafe-meaning.html
1996 /// [soundness]: https://rust-lang.github.io/unsafe-code-guidelines/glossary.html#soundness-of-code--of-a-library
1997 /// [Reference]: ../reference/unsafety.html
1998 /// [proposal]: https://github.com/rust-lang/rfcs/pull/2585
1999 /// [discussion on Rust Internals]: https://internals.rust-lang.org/t/what-does-unsafe-mean/6696
2000 mod unsafe_keyword {}
2001
2002 #[doc(keyword = "use")]
2003 //
2004 /// Import or rename items from other crates or modules.
2005 ///
2006 /// Usually a `use` keyword is used to shorten the path required to refer to a module item.
2007 /// The keyword may appear in modules, blocks and even functions, usually at the top.
2008 ///
2009 /// The most basic usage of the keyword is `use path::to::item;`,
2010 /// though a number of convenient shortcuts are supported:
2011 ///
2012 ///   * Simultaneously binding a list of paths with a common prefix,
2013 ///     using the glob-like brace syntax `use a::b::{c, d, e::f, g::h::i};`
2014 ///   * Simultaneously binding a list of paths with a common prefix and their common parent module,
2015 ///     using the [`self`] keyword, such as `use a::b::{self, c, d::e};`
2016 ///   * Rebinding the target name as a new local name, using the syntax `use p::q::r as x;`.
2017 ///     This can also be used with the last two features: `use a::b::{self as ab, c as abc}`.
2018 ///   * Binding all paths matching a given prefix,
2019 ///     using the asterisk wildcard syntax `use a::b::*;`.
2020 ///   * Nesting groups of the previous features multiple times,
2021 ///     such as `use a::b::{self as ab, c, d::{*, e::f}};`
2022 ///   * Reexporting with visibility modifiers such as `pub use a::b;`
2023 ///   * Importing with `_` to only import the methods of a trait without binding it to a name
2024 ///     (to avoid conflict for example): `use ::std::io::Read as _;`.
2025 ///
2026 /// Using path qualifiers like [`crate`], [`super`] or [`self`] is supported: `use crate::a::b;`.
2027 ///
2028 /// Note that when the wildcard `*` is used on a type, it does not import its methods (though
2029 /// for `enum`s it imports the variants, as shown in the example below).
2030 ///
2031 /// ```compile_fail,edition2018
2032 /// enum ExampleEnum {
2033 ///     VariantA,
2034 ///     VariantB,
2035 /// }
2036 ///
2037 /// impl ExampleEnum {
2038 ///     fn new() -> Self {
2039 ///         Self::VariantA
2040 ///     }
2041 /// }
2042 ///
2043 /// use ExampleEnum::*;
2044 ///
2045 /// // Compiles.
2046 /// let _ = VariantA;
2047 ///
2048 /// // Does not compile !
2049 /// let n = new();
2050 /// ```
2051 ///
2052 /// For more information on `use` and paths in general, see the [Reference].
2053 ///
2054 /// The differences about paths and the `use` keyword between the 2015 and 2018 editions
2055 /// can also be found in the [Reference].
2056 ///
2057 /// [`crate`]: keyword.crate.html
2058 /// [`self`]: keyword.self.html
2059 /// [`super`]: keyword.super.html
2060 /// [Reference]: ../reference/items/use-declarations.html
2061 mod use_keyword {}
2062
2063 #[doc(keyword = "where")]
2064 //
2065 /// Add constraints that must be upheld to use an item.
2066 ///
2067 /// `where` allows specifying constraints on lifetime and generic parameters.
2068 /// The [RFC] introducing `where` contains detailed informations about the
2069 /// keyword.
2070 ///
2071 /// # Examples
2072 ///
2073 /// `where` can be used for constraints with traits:
2074 ///
2075 /// ```rust
2076 /// fn new<T: Default>() -> T {
2077 ///     T::default()
2078 /// }
2079 ///
2080 /// fn new_where<T>() -> T
2081 /// where
2082 ///     T: Default,
2083 /// {
2084 ///     T::default()
2085 /// }
2086 ///
2087 /// assert_eq!(0.0, new());
2088 /// assert_eq!(0.0, new_where());
2089 ///
2090 /// assert_eq!(0, new());
2091 /// assert_eq!(0, new_where());
2092 /// ```
2093 ///
2094 /// `where` can also be used for lifetimes.
2095 ///
2096 /// This compiles because `longer` outlives `shorter`, thus the constraint is
2097 /// respected:
2098 ///
2099 /// ```rust
2100 /// fn select<'short, 'long>(s1: &'short str, s2: &'long str, second: bool) -> &'short str
2101 /// where
2102 ///     'long: 'short,
2103 /// {
2104 ///     if second { s2 } else { s1 }
2105 /// }
2106 ///
2107 /// let outer = String::from("Long living ref");
2108 /// let longer = &outer;
2109 /// {
2110 ///     let inner = String::from("Short living ref");
2111 ///     let shorter = &inner;
2112 ///
2113 ///     assert_eq!(select(shorter, longer, false), shorter);
2114 ///     assert_eq!(select(shorter, longer, true), longer);
2115 /// }
2116 /// ```
2117 ///
2118 /// On the other hand, this will not compile because the `where 'b: 'a` clause
2119 /// is missing: the `'b` lifetime is not known to live at least as long as `'a`
2120 /// which means this function cannot ensure it always returns a valid reference:
2121 ///
2122 /// ```rust,compile_fail,E0623
2123 /// fn select<'a, 'b>(s1: &'a str, s2: &'b str, second: bool) -> &'a str
2124 /// {
2125 ///     if second { s2 } else { s1 }
2126 /// }
2127 /// ```
2128 ///
2129 /// `where` can also be used to express more complicated constraints that cannot
2130 /// be written with the `<T: Trait>` syntax:
2131 ///
2132 /// ```rust
2133 /// fn first_or_default<I>(mut i: I) -> I::Item
2134 /// where
2135 ///     I: Iterator,
2136 ///     I::Item: Default,
2137 /// {
2138 ///     i.next().unwrap_or_else(I::Item::default)
2139 /// }
2140 ///
2141 /// assert_eq!(first_or_default(vec![1, 2, 3].into_iter()), 1);
2142 /// assert_eq!(first_or_default(Vec::<i32>::new().into_iter()), 0);
2143 /// ```
2144 ///
2145 /// `where` is available anywhere generic and lifetime parameters are available,
2146 /// as can be seen with the [`Cow`](crate::borrow::Cow) type from the standard
2147 /// library:
2148 ///
2149 /// ```rust
2150 /// # #![allow(dead_code)]
2151 /// pub enum Cow<'a, B>
2152 /// where
2153 ///     B: 'a + ToOwned + ?Sized,
2154 ///  {
2155 ///     Borrowed(&'a B),
2156 ///     Owned(<B as ToOwned>::Owned),
2157 /// }
2158 /// ```
2159 ///
2160 /// [RFC]: https://github.com/rust-lang/rfcs/blob/master/text/0135-where.md
2161 mod where_keyword {}
2162
2163 // 2018 Edition keywords
2164
2165 #[doc(keyword = "async")]
2166 //
2167 /// Return a [`Future`] instead of blocking the current thread.
2168 ///
2169 /// Use `async` in front of `fn`, `closure`, or a `block` to turn the marked code into a `Future`.
2170 /// As such the code will not be run immediately, but will only be evaluated when the returned
2171 /// future is `.await`ed.
2172 ///
2173 /// We have written an [async book] detailing async/await and trade-offs compared to using threads.
2174 ///
2175 /// ## Editions
2176 ///
2177 /// `async` is a keyword from the 2018 edition onwards.
2178 ///
2179 /// It is available for use in stable rust from version 1.39 onwards.
2180 ///
2181 /// [`Future`]: ./future/trait.Future.html
2182 /// [async book]: https://rust-lang.github.io/async-book/
2183 mod async_keyword {}
2184
2185 #[doc(keyword = "await")]
2186 //
2187 /// Suspend execution until the result of a [`Future`] is ready.
2188 ///
2189 /// `.await`ing a future will suspend the current function's execution until the `executor`
2190 /// has run the future to completion.
2191 ///
2192 /// Read the [async book] for details on how async/await and executors work.
2193 ///
2194 /// ## Editions
2195 ///
2196 /// `await` is a keyword from the 2018 edition onwards.
2197 ///
2198 /// It is available for use in stable rust from version 1.39 onwards.
2199 ///
2200 /// [`Future`]: ./future/trait.Future.html
2201 /// [async book]: https://rust-lang.github.io/async-book/
2202 mod await_keyword {}
2203
2204 #[doc(keyword = "dyn")]
2205 //
2206 /// `dyn` is a prefix of a [trait object]'s type.
2207 ///
2208 /// The `dyn` keyword is used to highlight that calls to methods on the associated `Trait`
2209 /// are dynamically dispatched. To use the trait this way, it must be 'object safe'.
2210 ///
2211 /// Unlike generic parameters or `impl Trait`, the compiler does not know the concrete type that
2212 /// is being passed. That is, the type has been [erased].
2213 /// As such, a `dyn Trait` reference contains _two_ pointers.
2214 /// One pointer goes to the data (e.g., an instance of a struct).
2215 /// Another pointer goes to a map of method call names to function pointers
2216 /// (known as a virtual method table or vtable).
2217 ///
2218 /// At run-time, when a method needs to be called on the `dyn Trait`, the vtable is consulted to get
2219 /// the function pointer and then that function pointer is called.
2220 ///
2221 /// ## Trade-offs
2222 ///
2223 /// The above indirection is the additional runtime cost of calling a function on a `dyn Trait`.
2224 /// Methods called by dynamic dispatch generally cannot be inlined by the compiler.
2225 ///
2226 /// However, `dyn Trait` is likely to produce smaller code than `impl Trait` / generic parameters as
2227 /// the method won't be duplicated for each concrete type.
2228 ///
2229 /// Read more about `object safety` and [trait object]s.
2230 ///
2231 /// [trait object]: ../book/ch17-02-trait-objects.html
2232 /// [erased]: https://en.wikipedia.org/wiki/Type_erasure
2233 mod dyn_keyword {}
2234
2235 #[doc(keyword = "union")]
2236 //
2237 /// The [Rust equivalent of a C-style union][union].
2238 ///
2239 /// A `union` looks like a [`struct`] in terms of declaration, but all of its
2240 /// fields exist in the same memory, superimposed over one another. For instance,
2241 /// if we wanted some bits in memory that we sometimes interpret as a `u32` and
2242 /// sometimes as an `f32`, we could write:
2243 ///
2244 /// ```rust
2245 /// union IntOrFloat {
2246 ///     i: u32,
2247 ///     f: f32,
2248 /// }
2249 ///
2250 /// let mut u = IntOrFloat { f: 1.0 };
2251 /// // Reading the fields of an union is always unsafe
2252 /// assert_eq!(unsafe { u.i }, 1065353216);
2253 /// // Updating through any of the field will modify all of them
2254 /// u.i = 1073741824;
2255 /// assert_eq!(unsafe { u.f }, 2.0);
2256 /// ```
2257 ///
2258 /// # Matching on unions
2259 ///
2260 /// It is possible to use pattern matching on `union`s. A single field name must
2261 /// be used and it must match the name of one of the `union`'s field.
2262 /// Like reading from a `union`, pattern matching on a `union` requires `unsafe`.
2263 ///
2264 /// ```rust
2265 /// union IntOrFloat {
2266 ///     i: u32,
2267 ///     f: f32,
2268 /// }
2269 ///
2270 /// let u = IntOrFloat { f: 1.0 };
2271 ///
2272 /// unsafe {
2273 ///     match u {
2274 ///         IntOrFloat { i: 10 } => println!("Found exactly ten!"),
2275 ///         // Matching the field `f` provides an `f32`.
2276 ///         IntOrFloat { f } => println!("Found f = {} !", f),
2277 ///     }
2278 /// }
2279 /// ```
2280 ///
2281 /// # References to union fields
2282 ///
2283 /// All fields in a `union` are all at the same place in memory which means
2284 /// borrowing one borrows the entire `union`, for the same lifetime:
2285 ///
2286 /// ```rust,compile_fail,E0502
2287 /// union IntOrFloat {
2288 ///     i: u32,
2289 ///     f: f32,
2290 /// }
2291 ///
2292 /// let mut u = IntOrFloat { f: 1.0 };
2293 ///
2294 /// let f = unsafe { &u.f };
2295 /// // This will not compile because the field has already been borrowed, even
2296 /// // if only immutably
2297 /// let i = unsafe { &mut u.i };
2298 ///
2299 /// *i = 10;
2300 /// println!("f = {} and i = {}", f, i);
2301 /// ```
2302 ///
2303 /// See the [Reference][union] for more informations on `union`s.
2304 ///
2305 /// [`struct`]: keyword.struct.html
2306 /// [union]: ../reference/items/unions.html
2307 mod union_keyword {}