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