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