]> git.lizzy.rs Git - rust.git/blob - src/libstd/keyword_docs.rs
Auto merge of #68943 - ecstatic-morse:no-useless-drop-on-enum-variants, r=matthewjasper
[rust.git] / src / libstd / keyword_docs.rs
1 #[doc(keyword = "as")]
2 //
3 /// Cast between types, or rename an import.
4 ///
5 /// `as` is most commonly used to turn primitive types into other primitive types, but it has other
6 /// uses that include turning pointers into addresses, addresses into pointers, and pointers into
7 /// other pointers.
8 ///
9 /// ```rust
10 /// let thing1: u8 = 89.0 as u8;
11 /// assert_eq!('B' as u32, 66);
12 /// assert_eq!(thing1 as char, 'Y');
13 /// let thing2: f32 = thing1 as f32 + 10.5;
14 /// assert_eq!(true as u8 + thing2 as u8, 100);
15 /// ```
16 ///
17 /// In general, any cast that can be performed via ascribing the type can also be done using `as`,
18 /// so instead of writing `let x: u32 = 123`, you can write `let x = 123 as u32` (Note: `let x: u32
19 /// = 123` would be best in that situation). The same is not true in the other direction, however,
20 /// explicitly using `as` allows a few more coercions that aren't allowed implicitly, such as
21 /// changing the type of a raw pointer or turning closures into raw pointers.
22 ///
23 /// Other places `as` is used include as extra syntax for [`crate`] and `use`, to change the name
24 /// something is imported as.
25 ///
26 /// For more information on what `as` is capable of, see the [Reference]
27 ///
28 /// [Reference]: ../reference/expressions/operator-expr.html#type-cast-expressions
29 /// [`crate`]: keyword.crate.html
30 mod as_keyword {}
31
32 #[doc(keyword = "break")]
33 //
34 /// Exit early from a loop.
35 ///
36 /// When `break` is encountered, execution of the associated loop body is
37 /// immediately terminated.
38 ///
39 /// ```rust
40 /// let mut last = 0;
41 ///
42 /// for x in 1..100 {
43 ///     if x > 12 {
44 ///         break;
45 ///     }
46 ///     last = x;
47 /// }
48 ///
49 /// assert_eq!(last, 12);
50 /// println!("{}", last);
51 /// ```
52 ///
53 /// A break expression is normally associated with the innermost loop enclosing the
54 /// `break` but a label can be used to specify which enclosing loop is affected.
55 ///
56 ///```rust
57 /// 'outer: for i in 1..=5 {
58 ///     println!("outer iteration (i): {}", i);
59 ///
60 ///     '_inner: for j in 1..=200 {
61 ///         println!("    inner iteration (j): {}", j);
62 ///         if j >= 3 {
63 ///             // breaks from inner loop, let's outer loop continue.
64 ///             break;
65 ///         }
66 ///         if i >= 2 {
67 ///             // breaks from outer loop, and directly to "Bye".
68 ///             break 'outer;
69 ///         }
70 ///     }
71 /// }
72 /// println!("Bye.");
73 ///```
74 ///
75 /// When associated with `loop`, a break expression may be used to return a value from that loop.
76 /// This is only valid with `loop` and not with any other type of loop.
77 /// If no value is specified, `break;` returns `()`.
78 /// Every `break` within a loop must return the same type.
79 ///
80 /// ```rust
81 /// let (mut a, mut b) = (1, 1);
82 /// let result = loop {
83 ///     if b > 10 {
84 ///         break b;
85 ///     }
86 ///     let c = a + b;
87 ///     a = b;
88 ///     b = c;
89 /// };
90 /// // first number in Fibonacci sequence over 10:
91 /// assert_eq!(result, 13);
92 /// println!("{}", result);
93 /// ```
94 ///
95 /// For more details consult the [Reference on "break expression"] and the [Reference on "break and
96 /// loop values"].
97 ///
98 /// [Reference on "break expression"]: ../reference/expressions/loop-expr.html#break-expressions
99 /// [Reference on "break and loop values"]:
100 /// ../reference/expressions/loop-expr.html#break-and-loop-values
101 ///
102 mod break_keyword {}
103
104 #[doc(keyword = "const")]
105 //
106 /// Compile-time constants and deterministic functions.
107 ///
108 /// Sometimes a certain value is used many times throughout a program, and it can become
109 /// inconvenient to copy it over and over. What's more, it's not always possible or desirable to
110 /// make it a variable that gets carried around to each function that needs it. In these cases, the
111 /// `const` keyword provides a convenient alternative to code duplication.
112 ///
113 /// ```rust
114 /// const THING: u32 = 0xABAD1DEA;
115 ///
116 /// let foo = 123 + THING;
117 /// ```
118 ///
119 /// Constants must be explicitly typed, unlike with `let` you can't ignore its type and let the
120 /// compiler figure it out. Any constant value can be defined in a const, which in practice happens
121 /// to be most things that would be reasonable to have a constant (barring `const fn`s). For
122 /// example, you can't have a File as a `const`.
123 ///
124 /// The only lifetime allowed in a constant is `'static`, which is the lifetime that encompasses
125 /// all others in a Rust program. For example, if you wanted to define a constant string, it would
126 /// look like this:
127 ///
128 /// ```rust
129 /// const WORDS: &'static str = "hello rust!";
130 /// ```
131 ///
132 /// Thanks to static lifetime elision, you usually don't have to explicitly use 'static:
133 ///
134 /// ```rust
135 /// const WORDS: &str = "hello convenience!";
136 /// ```
137 ///
138 /// `const` items looks remarkably similar to `static` items, which introduces some confusion as
139 /// to which one should be used at which times. To put it simply, constants are inlined wherever
140 /// they're used, making using them identical to simply replacing the name of the const with its
141 /// value. Static variables on the other hand point to a single location in memory, which all
142 /// accesses share. This means that, unlike with constants, they can't have destructors, and act as
143 /// a single value across the entire codebase.
144 ///
145 /// Constants, as with statics, should always be in SCREAMING_SNAKE_CASE.
146 ///
147 /// The `const` keyword is also used in raw pointers in combination with `mut`, as seen in `*const
148 /// T` and `*mut T`. More about that can be read at the [pointer] primitive part of the Rust docs.
149 ///
150 /// For more detail on `const`, see the [Rust Book] or the [Reference]
151 ///
152 /// [pointer]: primitive.pointer.html
153 /// [Rust Book]:
154 /// ../book/ch03-01-variables-and-mutability.html#differences-between-variables-and-constants
155 /// [Reference]: ../reference/items/constant-items.html
156 mod const_keyword {}
157
158 #[doc(keyword = "continue")]
159 //
160 /// Skip to the next iteration of a loop.
161 ///
162 /// When `continue` is encountered, the current iteration is terminated, returning control to the
163 /// loop head, typically continuing with the next iteration.
164 ///
165 ///```rust
166 /// // Printing odd numbers by skipping even ones
167 /// for number in 1..=10 {
168 ///     if number % 2 == 0 {
169 ///         continue;
170 ///     }
171 ///     println!("{}", number);
172 /// }
173 ///```
174 ///
175 /// Like `break`, `continue` is normally associated with the innermost enclosing loop, but labels
176 /// may be used to specify the affected loop.
177 ///
178 ///```rust
179 /// // Print Odd numbers under 30 with unit <= 5
180 /// 'tens: for ten in 0..3 {
181 ///     '_units: for unit in 0..=9 {
182 ///         if unit % 2 == 0 {
183 ///             continue;
184 ///         }
185 ///         if unit > 5 {
186 ///             continue 'tens;
187 ///         }
188 ///         println!("{}", ten * 10 + unit);
189 ///     }
190 /// }
191 ///```
192 ///
193 /// See [continue expressions] from the reference for more details.
194 ///
195 /// [continue expressions]: ../reference/expressions/loop-expr.html#continue-expressions
196 mod continue_keyword {}
197
198 #[doc(keyword = "crate")]
199 //
200 /// A Rust binary or library.
201 ///
202 /// The primary use of the `crate` keyword is as a part of `extern crate` declarations, which are
203 /// used to specify a dependency on a crate external to the one it's declared in. Crates are the
204 /// fundamental compilation unit of Rust code, and can be seen as libraries or projects. More can
205 /// be read about crates in the [Reference].
206 ///
207 /// ```rust ignore
208 /// extern crate rand;
209 /// extern crate my_crate as thing;
210 /// extern crate std; // implicitly added to the root of every Rust project
211 /// ```
212 ///
213 /// The `as` keyword can be used to change what the crate is referred to as in your project. If a
214 /// crate name includes a dash, it is implicitly imported with the dashes replaced by underscores.
215 ///
216 /// `crate` can also be used as in conjunction with `pub` to signify that the item it's attached to
217 /// is public only to other members of the same crate it's in.
218 ///
219 /// ```rust
220 /// # #[allow(unused_imports)]
221 /// pub(crate) use std::io::Error as IoError;
222 /// pub(crate) enum CoolMarkerType { }
223 /// pub struct PublicThing {
224 ///     pub(crate) semi_secret_thing: bool,
225 /// }
226 /// ```
227 ///
228 /// `crate` is also used to represent the absolute path of a module, where `crate` refers to the
229 /// root of the current crate. For instance, `crate::foo::bar` refers to the name `bar` inside the
230 /// module `foo`, from anywhere else in the same crate.
231 ///
232 /// [Reference]: ../reference/items/extern-crates.html
233 mod crate_keyword {}
234
235 #[doc(keyword = "else")]
236 //
237 /// What to do when an [`if`] condition does not hold.
238 ///
239 /// The documentation for this keyword is [not yet complete]. Pull requests welcome!
240 ///
241 /// [`if`]: keyword.if.html
242 /// [not yet complete]: https://github.com/rust-lang/rust/issues/34601
243 mod else_keyword {}
244
245 #[doc(keyword = "enum")]
246 //
247 /// A type that can be any one of several variants.
248 ///
249 /// Enums in Rust are similar to those of other compiled languages like C, but have important
250 /// differences that make them considerably more powerful. What Rust calls enums are more commonly
251 /// known as [Algebraic Data Types][ADT] if you're coming from a functional programming background.
252 /// The important detail is that each enum variant can have data to go along with it.
253 ///
254 /// ```rust
255 /// # struct Coord;
256 /// enum SimpleEnum {
257 ///     FirstVariant,
258 ///     SecondVariant,
259 ///     ThirdVariant,
260 /// }
261 ///
262 /// enum Location {
263 ///     Unknown,
264 ///     Anonymous,
265 ///     Known(Coord),
266 /// }
267 ///
268 /// enum ComplexEnum {
269 ///     Nothing,
270 ///     Something(u32),
271 ///     LotsOfThings {
272 ///         usual_struct_stuff: bool,
273 ///         blah: String,
274 ///     }
275 /// }
276 ///
277 /// enum EmptyEnum { }
278 /// ```
279 ///
280 /// The first enum shown is the usual kind of enum you'd find in a C-style language. The second
281 /// shows off a hypothetical example of something storing location data, with `Coord` being any
282 /// other type that's needed, for example a struct. The third example demonstrates the kind of
283 /// data a variant can store, ranging from nothing, to a tuple, to an anonymous struct.
284 ///
285 /// Instantiating enum variants involves explicitly using the enum's name as its namespace,
286 /// followed by one of its variants. `SimpleEnum::SecondVariant` would be an example from above.
287 /// When data follows along with a variant, such as with rust's built-in [`Option`] type, the data
288 /// is added as the type describes, for example `Option::Some(123)`. The same follows with
289 /// struct-like variants, with things looking like `ComplexEnum::LotsOfThings { usual_struct_stuff:
290 /// true, blah: "hello!".to_string(), }`. Empty Enums are similar to () in that they cannot be
291 /// instantiated at all, and are used mainly to mess with the type system in interesting ways.
292 ///
293 /// For more information, take a look at the [Rust Book] or the [Reference]
294 ///
295 /// [ADT]: https://en.wikipedia.org/wiki/Algebraic_data_type
296 /// [`Option`]: option/enum.Option.html
297 /// [Rust Book]: ../book/ch06-01-defining-an-enum.html
298 /// [Reference]: ../reference/items/enumerations.html
299 mod enum_keyword {}
300
301 #[doc(keyword = "extern")]
302 //
303 /// Link to or import external code.
304 ///
305 /// The `extern` keyword is used in two places in Rust. One is in conjunction with the [`crate`]
306 /// keyword to make your Rust code aware of other Rust crates in your project, i.e., `extern crate
307 /// lazy_static;`. The other use is in foreign function interfaces (FFI).
308 ///
309 /// `extern` is used in two different contexts within FFI. The first is in the form of external
310 /// blocks, for declaring function interfaces that Rust code can call foreign code by.
311 ///
312 /// ```rust ignore
313 /// #[link(name = "my_c_library")]
314 /// extern "C" {
315 ///     fn my_c_function(x: i32) -> bool;
316 /// }
317 /// ```
318 ///
319 /// This code would attempt to link with `libmy_c_library.so` on unix-like systems and
320 /// `my_c_library.dll` on Windows at runtime, and panic if it can't find something to link to. Rust
321 /// code could then use `my_c_function` as if it were any other unsafe Rust function. Working with
322 /// non-Rust languages and FFI is inherently unsafe, so wrappers are usually built around C APIs.
323 ///
324 /// The mirror use case of FFI is also done via the `extern` keyword:
325 ///
326 /// ```rust
327 /// #[no_mangle]
328 /// pub extern fn callable_from_c(x: i32) -> bool {
329 ///     x % 3 == 0
330 /// }
331 /// ```
332 ///
333 /// If compiled as a dylib, the resulting .so could then be linked to from a C library, and the
334 /// function could be used as if it was from any other library.
335 ///
336 /// For more information on FFI, check the [Rust book] or the [Reference].
337 ///
338 /// [Rust book]:
339 /// ../book/ch19-01-unsafe-rust.html#using-extern-functions-to-call-external-code
340 /// [Reference]: ../reference/items/external-blocks.html
341 mod extern_keyword {}
342
343 #[doc(keyword = "false")]
344 //
345 /// A value of type [`bool`] representing logical **false**.
346 ///
347 /// The documentation for this keyword is [not yet complete]. Pull requests welcome!
348 ///
349 /// [`bool`]: primitive.bool.html
350 /// [not yet complete]: https://github.com/rust-lang/rust/issues/34601
351 mod false_keyword {}
352
353 #[doc(keyword = "fn")]
354 //
355 /// A function or function pointer.
356 ///
357 /// Functions are the primary way code is executed within Rust. Function blocks, usually just
358 /// called functions, can be defined in a variety of different places and be assigned many
359 /// different attributes and modifiers.
360 ///
361 /// Standalone functions that just sit within a module not attached to anything else are common,
362 /// but most functions will end up being inside [`impl`] blocks, either on another type itself, or
363 /// as a trait impl for that type.
364 ///
365 /// ```rust
366 /// fn standalone_function() {
367 ///     // code
368 /// }
369 ///
370 /// pub fn public_thing(argument: bool) -> String {
371 ///     // code
372 ///     # "".to_string()
373 /// }
374 ///
375 /// struct Thing {
376 ///     foo: i32,
377 /// }
378 ///
379 /// impl Thing {
380 ///     pub fn new() -> Self {
381 ///         Self {
382 ///             foo: 42,
383 ///         }
384 ///     }
385 /// }
386 /// ```
387 ///
388 /// In addition to presenting fixed types in the form of `fn name(arg: type, ..) -> return_type`,
389 /// functions can also declare a list of type parameters along with trait bounds that they fall
390 /// into.
391 ///
392 /// ```rust
393 /// fn generic_function<T: Clone>(x: T) -> (T, T, T) {
394 ///     (x.clone(), x.clone(), x.clone())
395 /// }
396 ///
397 /// fn generic_where<T>(x: T) -> T
398 ///     where T: std::ops::Add<Output = T> + Copy
399 /// {
400 ///     x + x + x
401 /// }
402 /// ```
403 ///
404 /// Declaring trait bounds in the angle brackets is functionally identical to using a `where`
405 /// clause. It's up to the programmer to decide which works better in each situation, but `where`
406 /// tends to be better when things get longer than one line.
407 ///
408 /// Along with being made public via `pub`, `fn` can also have an [`extern`] added for use in
409 /// FFI.
410 ///
411 /// For more information on the various types of functions and how they're used, consult the [Rust
412 /// book] or the [Reference].
413 ///
414 /// [`impl`]: keyword.impl.html
415 /// [`extern`]: keyword.extern.html
416 /// [Rust book]: ../book/ch03-03-how-functions-work.html
417 /// [Reference]: ../reference/items/functions.html
418 mod fn_keyword {}
419
420 #[doc(keyword = "for")]
421 //
422 /// Iteration with [`in`], trait implementation with [`impl`], or [higher-ranked trait bounds]
423 /// (`for<'a>`).
424 ///
425 /// The `for` keyword is used in many syntactic locations:
426 ///
427 /// * `for` is used in for-in-loops (see below).
428 /// * `for` is used when implementing traits as in `impl Trait for Type` (see [`impl`] for more info
429 ///   on that).
430 /// * `for` is also used for [higher-ranked trait bounds] as in `for<'a> &'a T: PartialEq<i32>`.
431 ///
432 /// for-in-loops, or to be more precise, iterator loops, are a simple syntactic sugar over a common
433 /// practice within Rust, which is to loop over an iterator until that iterator returns `None` (or
434 /// `break` is called).
435 ///
436 /// ```rust
437 /// for i in 0..5 {
438 ///     println!("{}", i * 2);
439 /// }
440 ///
441 /// for i in std::iter::repeat(5) {
442 ///     println!("turns out {} never stops being 5", i);
443 ///     break; // would loop forever otherwise
444 /// }
445 ///
446 /// 'outer: for x in 5..50 {
447 ///     for y in 0..10 {
448 ///         if x == y {
449 ///             break 'outer;
450 ///         }
451 ///     }
452 /// }
453 /// ```
454 ///
455 /// As shown in the example above, `for` loops (along with all other loops) can be tagged, using
456 /// similar syntax to lifetimes (only visually similar, entirely distinct in practice). Giving the
457 /// same tag to `break` breaks the tagged loop, which is useful for inner loops. It is definitely
458 /// not a goto.
459 ///
460 /// A `for` loop expands as shown:
461 ///
462 /// ```rust
463 /// # fn code() { }
464 /// # let iterator = 0..2;
465 /// for loop_variable in iterator {
466 ///     code()
467 /// }
468 /// ```
469 ///
470 /// ```rust
471 /// # fn code() { }
472 /// # let iterator = 0..2;
473 /// {
474 ///     let mut _iter = std::iter::IntoIterator::into_iter(iterator);
475 ///     loop {
476 ///         match _iter.next() {
477 ///             Some(loop_variable) => {
478 ///                 code()
479 ///             },
480 ///             None => break,
481 ///         }
482 ///     }
483 /// }
484 /// ```
485 ///
486 /// More details on the functionality shown can be seen at the [`IntoIterator`] docs.
487 ///
488 /// For more information on for-loops, see the [Rust book] or the [Reference].
489 ///
490 /// [`in`]: keyword.in.html
491 /// [`impl`]: keyword.impl.html
492 /// [higher-ranked trait bounds]: ../reference/trait-bounds.html#higher-ranked-trait-bounds
493 /// [`IntoIterator`]: iter/trait.IntoIterator.html
494 /// [Rust book]:
495 /// ../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
496 /// [Reference]: ../reference/expressions/loop-expr.html#iterator-loops
497 mod for_keyword {}
498
499 #[doc(keyword = "if")]
500 //
501 /// Evaluate a block if a condition holds.
502 ///
503 /// `if` is a familiar construct to most programmers, and is the main way you'll often do logic in
504 /// your code. However, unlike in most languages, `if` blocks can also act as expressions.
505 ///
506 /// ```rust
507 /// # let rude = true;
508 /// if 1 == 2 {
509 ///     println!("whoops, mathematics broke");
510 /// } else {
511 ///     println!("everything's fine!");
512 /// }
513 ///
514 /// let greeting = if rude {
515 ///     "sup nerd."
516 /// } else {
517 ///     "hello, friend!"
518 /// };
519 ///
520 /// if let Ok(x) = "123".parse::<i32>() {
521 ///     println!("{} double that and you get {}!", greeting, x * 2);
522 /// }
523 /// ```
524 ///
525 /// Shown above are the three typical forms an `if` block comes in. First is the usual kind of
526 /// thing you'd see in many languages, with an optional `else` block. Second uses `if` as an
527 /// expression, which is only possible if all branches return the same type. An `if` expression can
528 /// be used everywhere you'd expect. The third kind of `if` block is an `if let` block, which
529 /// behaves similarly to using a `match` expression:
530 ///
531 /// ```rust
532 /// if let Some(x) = Some(123) {
533 ///     // code
534 ///     # let _ = x;
535 /// } else {
536 ///     // something else
537 /// }
538 ///
539 /// match Some(123) {
540 ///     Some(x) => {
541 ///         // code
542 ///         # let _ = x;
543 ///     },
544 ///     _ => {
545 ///         // something else
546 ///     },
547 /// }
548 /// ```
549 ///
550 /// Each kind of `if` expression can be mixed and matched as needed.
551 ///
552 /// ```rust
553 /// if true == false {
554 ///     println!("oh no");
555 /// } else if "something" == "other thing" {
556 ///     println!("oh dear");
557 /// } else if let Some(200) = "blarg".parse::<i32>().ok() {
558 ///     println!("uh oh");
559 /// } else {
560 ///     println!("phew, nothing's broken");
561 /// }
562 /// ```
563 ///
564 /// The `if` keyword is used in one other place in Rust, namely as a part of pattern matching
565 /// itself, allowing patterns such as `Some(x) if x > 200` to be used.
566 ///
567 /// For more information on `if` expressions, see the [Rust book] or the [Reference].
568 ///
569 /// [Rust book]: ../book/ch03-05-control-flow.html#if-expressions
570 /// [Reference]: ../reference/expressions/if-expr.html
571 mod if_keyword {}
572
573 #[doc(keyword = "impl")]
574 //
575 /// Implement some functionality for a type.
576 ///
577 /// The `impl` keyword is primarily used to define implementations on types. Inherent
578 /// implementations are standalone, while trait implementations are used to implement traits for
579 /// types, or other traits.
580 ///
581 /// Functions and consts can both be defined in an implementation. A function defined in an
582 /// `impl` block can be standalone, meaning it would be called like `Foo::bar()`. If the function
583 /// takes `self`, `&self`, or `&mut self` as its first argument, it can also be called using
584 /// method-call syntax, a familiar feature to any object oriented programmer, like `foo.bar()`.
585 ///
586 /// ```rust
587 /// struct Example {
588 ///     number: i32,
589 /// }
590 ///
591 /// impl Example {
592 ///     fn boo() {
593 ///         println!("boo! Example::boo() was called!");
594 ///     }
595 ///
596 ///     fn answer(&mut self) {
597 ///         self.number += 42;
598 ///     }
599 ///
600 ///     fn get_number(&self) -> i32 {
601 ///         self.number
602 ///     }
603 /// }
604 ///
605 /// trait Thingy {
606 ///     fn do_thingy(&self);
607 /// }
608 ///
609 /// impl Thingy for Example {
610 ///     fn do_thingy(&self) {
611 ///         println!("doing a thing! also, number is {}!", self.number);
612 ///     }
613 /// }
614 /// ```
615 ///
616 /// For more information on implementations, see the [Rust book][book1] or the [Reference].
617 ///
618 /// The other use of the `impl` keyword is in `impl Trait` syntax, which can be seen as a shorthand
619 /// for "a concrete type that implements this trait". Its primary use is working with closures,
620 /// which have type definitions generated at compile time that can't be simply typed out.
621 ///
622 /// ```rust
623 /// fn thing_returning_closure() -> impl Fn(i32) -> bool {
624 ///     println!("here's a closure for you!");
625 ///     |x: i32| x % 3 == 0
626 /// }
627 /// ```
628 ///
629 /// For more information on `impl Trait` syntax, see the [Rust book][book2].
630 ///
631 /// [book1]: ../book/ch05-03-method-syntax.html
632 /// [Reference]: ../reference/items/implementations.html
633 /// [book2]: ../book/ch10-02-traits.html#returning-types-that-implement-traits
634 mod impl_keyword {}
635
636 #[doc(keyword = "in")]
637 //
638 /// Iterate over a series of values with [`for`].
639 ///
640 /// The documentation for this keyword is [not yet complete]. Pull requests welcome!
641 ///
642 /// [`for`]: keyword.for.html
643 /// [not yet complete]: https://github.com/rust-lang/rust/issues/34601
644 mod in_keyword {}
645
646 #[doc(keyword = "let")]
647 //
648 /// Bind a value to a variable.
649 ///
650 /// The primary use for the `let` keyword is in `let` statements, which are used to introduce a new
651 /// set of variables into the current scope, as given by a pattern.
652 ///
653 /// ```rust
654 /// # #![allow(unused_assignments)]
655 /// let thing1: i32 = 100;
656 /// let thing2 = 200 + thing1;
657 ///
658 /// let mut changing_thing = true;
659 /// changing_thing = false;
660 ///
661 /// let (part1, part2) = ("first", "second");
662 ///
663 /// struct Example {
664 ///     a: bool,
665 ///     b: u64,
666 /// }
667 ///
668 /// let Example { a, b: _ } = Example {
669 ///     a: true,
670 ///     b: 10004,
671 /// };
672 /// assert!(a);
673 /// ```
674 ///
675 /// The pattern is most commonly a single variable, which means no pattern matching is done and
676 /// the expression given is bound to the variable. Apart from that, patterns used in `let` bindings
677 /// can be as complicated as needed, given that the pattern is exhaustive. See the [Rust
678 /// book][book1] for more information on pattern matching. The type of the pattern is optionally
679 /// given afterwards, but if left blank is automatically inferred by the compiler if possible.
680 ///
681 /// Variables in Rust are immutable by default, and require the `mut` keyword to be made mutable.
682 ///
683 /// Multiple variables can be defined with the same name, known as shadowing. This doesn't affect
684 /// the original variable in any way beyond being unable to directly access it beyond the point of
685 /// shadowing. It continues to remain in scope, getting dropped only when it falls out of scope.
686 /// Shadowed variables don't need to have the same type as the variables shadowing them.
687 ///
688 /// ```rust
689 /// let shadowing_example = true;
690 /// let shadowing_example = 123.4;
691 /// let shadowing_example = shadowing_example as u32;
692 /// let mut shadowing_example = format!("cool! {}", shadowing_example);
693 /// shadowing_example += " something else!"; // not shadowing
694 /// ```
695 ///
696 /// Other places the `let` keyword is used include along with [`if`], in the form of `if let`
697 /// expressions. They're useful if the pattern being matched isn't exhaustive, such as with
698 /// enumerations. `while let` also exists, which runs a loop with a pattern matched value until
699 /// that pattern can't be matched.
700 ///
701 /// For more information on the `let` keyword, see the [Rust book][book2] or the [Reference]
702 ///
703 /// [book1]: ../book/ch06-02-match.html
704 /// [`if`]: keyword.if.html
705 /// [book2]: ../book/ch18-01-all-the-places-for-patterns.html#let-statements
706 /// [Reference]: ../reference/statements.html#let-statements
707 mod let_keyword {}
708
709 #[doc(keyword = "while")]
710 //
711 /// Loop while a condition is upheld.
712 ///
713 /// A `while` expression is used for predicate loops. The `while` expression runs the conditional
714 /// expression before running the loop body, then runs the loop body if the conditional
715 /// expression evaluates to `true`, or exits the loop otherwise.
716 ///
717 /// ```rust
718 /// let mut counter = 0;
719 ///
720 /// while counter < 10 {
721 ///     println!("{}", counter);
722 ///     counter += 1;
723 /// }
724 /// ```
725 ///
726 /// Like the [`for`] expression, we can use `break` and `continue`. A `while` expression
727 /// cannot break with a value and always evaluates to `()` unlike [`loop`].
728 ///
729 /// ```rust
730 /// let mut i = 1;
731 ///
732 /// while i < 100 {
733 ///     i *= 2;
734 ///     if i == 64 {
735 ///         break; // Exit when `i` is 64.
736 ///     }
737 /// }
738 /// ```
739 ///
740 /// As `if` expressions have their pattern matching variant in `if let`, so too do `while`
741 /// expressions with `while let`. The `while let` expression matches the pattern against the
742 /// expression, then runs the loop body if pattern matching succeeds, or exits the loop otherwise.
743 /// We can use `break` and `continue` in `while let` expressions just like in `while`.
744 ///
745 /// ```rust
746 /// let mut counter = Some(0);
747 ///
748 /// while let Some(i) = counter {
749 ///     if i == 10 {
750 ///         counter = None;
751 ///     } else {
752 ///         println!("{}", i);
753 ///         counter = Some (i + 1);
754 ///     }
755 /// }
756 /// ```
757 ///
758 /// For more information on `while` and loops in general, see the [reference].
759 ///
760 /// [`for`]: keyword.for.html
761 /// [`loop`]: keyword.loop.html
762 /// [reference]: ../reference/expressions/loop-expr.html#predicate-loops
763 mod while_keyword {}
764
765 #[doc(keyword = "loop")]
766 //
767 /// Loop indefinitely.
768 ///
769 /// `loop` is used to define the simplest kind of loop supported in Rust. It runs the code inside
770 /// it until the code uses `break` or the program exits.
771 ///
772 /// ```rust
773 /// loop {
774 ///     println!("hello world forever!");
775 ///     # break;
776 /// }
777 ///
778 /// let mut i = 1;
779 /// loop {
780 ///     println!("i is {}", i);
781 ///     if i > 100 {
782 ///         break;
783 ///     }
784 ///     i *= 2;
785 /// }
786 /// assert_eq!(i, 128);
787 /// ```
788 ///
789 /// Unlike the other kinds of loops in Rust (`while`, `while let`, and `for`), loops can be used as
790 /// expressions that return values via `break`.
791 ///
792 /// ```rust
793 /// let mut i = 1;
794 /// let something = loop {
795 ///     i *= 2;
796 ///     if i > 100 {
797 ///         break i;
798 ///     }
799 /// };
800 /// assert_eq!(something, 128);
801 /// ```
802 ///
803 /// Every `break` in a loop has to have the same type. When it's not explicitly giving something,
804 /// `break;` returns `()`.
805 ///
806 /// For more information on `loop` and loops in general, see the [Reference].
807 ///
808 /// [Reference]: ../reference/expressions/loop-expr.html
809 mod loop_keyword {}
810
811 #[doc(keyword = "match")]
812 //
813 /// Control flow based on pattern matching.
814 ///
815 /// `match` can be used to run code conditionally. Every pattern must
816 /// be handled exhaustively either explicitly or by using wildcards like
817 /// `_` in the `match`. Since `match` is an expression, values can also be
818 /// returned.
819 ///
820 /// ```rust
821 /// let opt = Option::None::<usize>;
822 /// let x = match opt {
823 ///     Some(int) => int,
824 ///     None => 10,
825 /// };
826 /// assert_eq!(x, 10);
827 ///
828 /// let a_number = Option::Some(10);
829 /// match a_number {
830 ///     Some(x) if x <= 5 => println!("0 to 5 num = {}", x),
831 ///     Some(x @ 6..=10) => println!("6 to 10 num = {}", x),
832 ///     None => panic!(),
833 ///     // all other numbers
834 ///     _ => panic!(),
835 /// }
836 /// ```
837 ///
838 /// `match` can be used to gain access to the inner members of an enum
839 /// and use them directly.
840 ///
841 /// ```rust
842 /// enum Outer {
843 ///     Double(Option<u8>, Option<String>),
844 ///     Single(Option<u8>),
845 ///     Empty
846 /// }
847 ///
848 /// let get_inner = Outer::Double(None, Some(String::new()));
849 /// match get_inner {
850 ///     Outer::Double(None, Some(st)) => println!("{}", st),
851 ///     Outer::Single(opt) => println!("{:?}", opt),
852 ///     _ => panic!(),
853 /// }
854 /// ```
855 ///
856 /// For more information on `match` and matching in general, see the [Reference].
857 ///
858 /// [Reference]: ../reference/expressions/match-expr.html
859 mod match_keyword {}
860
861 #[doc(keyword = "mod")]
862 //
863 /// Organize code into [modules].
864 ///
865 /// The documentation for this keyword is [not yet complete]. Pull requests welcome!
866 ///
867 /// [modules]: ../reference/items/modules.html
868 /// [not yet complete]: https://github.com/rust-lang/rust/issues/34601
869 mod mod_keyword {}
870
871 #[doc(keyword = "move")]
872 //
873 /// Capture a [closure]'s environment by value.
874 ///
875 /// `move` converts any variables captured by reference or mutable reference
876 /// to owned by value variables. The three [`Fn` trait]'s mirror the ways to capture
877 /// variables, when `move` is used, the closures is represented by the `FnOnce` trait.
878 ///
879 /// ```rust
880 /// let capture = "hello";
881 /// let closure = move || {
882 ///     println!("rust says {}", capture);
883 /// };
884 /// ```
885 ///
886 /// `move` is often used when [threads] are involved.
887 ///
888 /// ```rust
889 /// let x = 5;
890 ///
891 /// std::thread::spawn(move || {
892 ///     println!("captured {} by value", x)
893 /// }).join().unwrap();
894 ///
895 /// // x is no longer available
896 /// ```
897 ///
898 /// `move` is also valid before an async block.
899 ///
900 /// ```rust
901 /// let capture = "hello";
902 /// let block = async move {
903 ///     println!("rust says {} from async block", capture);
904 /// };
905 /// ```
906 ///
907 /// For more information on the `move` keyword, see the [closure]'s section
908 /// of the Rust book or the [threads] section
909 ///
910 /// [`Fn` trait]: ../std/ops/trait.Fn.html
911 /// [closure]: ../book/ch13-01-closures.html
912 /// [threads]: ../book/ch16-01-threads.html#using-move-closures-with-threads
913 mod move_keyword {}
914
915 #[doc(keyword = "mut")]
916 //
917 /// A mutable binding, reference, or pointer.
918 ///
919 /// The documentation for this keyword is [not yet complete]. Pull requests welcome!
920 ///
921 /// [not yet complete]: https://github.com/rust-lang/rust/issues/34601
922 mod mut_keyword {}
923
924 #[doc(keyword = "pub")]
925 //
926 /// Make an item visible to others.
927 ///
928 /// The documentation for this keyword is [not yet complete]. Pull requests welcome!
929 ///
930 /// [not yet complete]: https://github.com/rust-lang/rust/issues/34601
931 mod pub_keyword {}
932
933 #[doc(keyword = "ref")]
934 //
935 /// Bind by reference during pattern matching.
936 ///
937 /// The documentation for this keyword is [not yet complete]. Pull requests welcome!
938 ///
939 /// [not yet complete]: https://github.com/rust-lang/rust/issues/34601
940 mod ref_keyword {}
941
942 #[doc(keyword = "return")]
943 //
944 /// Return a value from a function.
945 ///
946 /// The documentation for this keyword is [not yet complete]. Pull requests welcome!
947 ///
948 /// [not yet complete]: https://github.com/rust-lang/rust/issues/34601
949 mod return_keyword {}
950
951 #[doc(keyword = "self")]
952 //
953 /// The receiver of a method, or the current module.
954 ///
955 /// The documentation for this keyword is [not yet complete]. Pull requests welcome!
956 ///
957 /// [not yet complete]: https://github.com/rust-lang/rust/issues/34601
958 mod self_keyword {}
959
960 #[doc(keyword = "Self")]
961 //
962 /// The implementing type within a [`trait`] or [`impl`] block, or the current type within a type
963 /// definition.
964 ///
965 /// The documentation for this keyword is [not yet complete]. Pull requests welcome!
966 ///
967 /// [`impl`]: keyword.impl.html
968 /// [`trait`]: keyword.trait.html
969 /// [not yet complete]: https://github.com/rust-lang/rust/issues/34601
970 mod self_upper_keyword {}
971
972 #[doc(keyword = "static")]
973 //
974 /// A place that is valid for the duration of a program.
975 ///
976 /// The documentation for this keyword is [not yet complete]. Pull requests welcome!
977 ///
978 /// [not yet complete]: https://github.com/rust-lang/rust/issues/34601
979 mod static_keyword {}
980
981 #[doc(keyword = "struct")]
982 //
983 /// A type that is composed of other types.
984 ///
985 /// Structs in Rust come in three flavors: Structs with named fields, tuple structs, and unit
986 /// structs.
987 ///
988 /// ```rust
989 /// struct Regular {
990 ///     field1: f32,
991 ///     field2: String,
992 ///     pub field3: bool
993 /// }
994 ///
995 /// struct Tuple(u32, String);
996 ///
997 /// struct Unit;
998 /// ```
999 ///
1000 /// Regular structs are the most commonly used. Each field defined within them has a name and a
1001 /// type, and once defined can be accessed using `example_struct.field` syntax. The fields of a
1002 /// struct share its mutability, so `foo.bar = 2;` would only be valid if `foo` was mutable. Adding
1003 /// `pub` to a field makes it visible to code in other modules, as well as allowing it to be
1004 /// directly accessed and modified.
1005 ///
1006 /// Tuple structs are similar to regular structs, but its fields have no names. They are used like
1007 /// tuples, with deconstruction possible via `let TupleStruct(x, y) = foo;` syntax. For accessing
1008 /// individual variables, the same syntax is used as with regular tuples, namely `foo.0`, `foo.1`,
1009 /// etc, starting at zero.
1010 ///
1011 /// Unit structs are most commonly used as marker. They have a size of zero bytes, but unlike empty
1012 /// enums they can be instantiated, making them isomorphic to the unit type `()`. Unit structs are
1013 /// useful when you need to implement a trait on something, but don't need to store any data inside
1014 /// it.
1015 ///
1016 /// # Instantiation
1017 ///
1018 /// Structs can be instantiated in different ways, all of which can be mixed and
1019 /// matched as needed. The most common way to make a new struct is via a constructor method such as
1020 /// `new()`, but when that isn't available (or you're writing the constructor itself), struct
1021 /// literal syntax is used:
1022 ///
1023 /// ```rust
1024 /// # struct Foo { field1: f32, field2: String, etc: bool }
1025 /// let example = Foo {
1026 ///     field1: 42.0,
1027 ///     field2: "blah".to_string(),
1028 ///     etc: true,
1029 /// };
1030 /// ```
1031 ///
1032 /// It's only possible to directly instantiate a struct using struct literal syntax when all of its
1033 /// fields are visible to you.
1034 ///
1035 /// There are a handful of shortcuts provided to make writing constructors more convenient, most
1036 /// common of which is the Field Init shorthand. When there is a variable and a field of the same
1037 /// name, the assignment can be simplified from `field: field` into simply `field`. The following
1038 /// example of a hypothetical constructor demonstrates this:
1039 ///
1040 /// ```rust
1041 /// struct User {
1042 ///     name: String,
1043 ///     admin: bool,
1044 /// }
1045 ///
1046 /// impl User {
1047 ///     pub fn new(name: String) -> Self {
1048 ///         Self {
1049 ///             name,
1050 ///             admin: false,
1051 ///         }
1052 ///     }
1053 /// }
1054 /// ```
1055 ///
1056 /// Another shortcut for struct instantiation is available, used when you need to make a new
1057 /// struct that has the same values as most of a previous struct of the same type, called struct
1058 /// update syntax:
1059 ///
1060 /// ```rust
1061 /// # struct Foo { field1: String, field2: () }
1062 /// # let thing = Foo { field1: "".to_string(), field2: () };
1063 /// let updated_thing = Foo {
1064 ///     field1: "a new value".to_string(),
1065 ///     ..thing
1066 /// };
1067 /// ```
1068 ///
1069 /// Tuple structs are instantiated in the same way as tuples themselves, except with the struct's
1070 /// name as a prefix: `Foo(123, false, 0.1)`.
1071 ///
1072 /// Empty structs are instantiated with just their name, and don't need anything else. `let thing =
1073 /// EmptyStruct;`
1074 ///
1075 /// # Style conventions
1076 ///
1077 /// Structs are always written in CamelCase, with few exceptions. While the trailing comma on a
1078 /// struct's list of fields can be omitted, it's usually kept for convenience in adding and
1079 /// removing fields down the line.
1080 ///
1081 /// For more information on structs, take a look at the [Rust Book][book] or the
1082 /// [Reference][reference].
1083 ///
1084 /// [`PhantomData`]: marker/struct.PhantomData.html
1085 /// [book]: ../book/ch05-01-defining-structs.html
1086 /// [reference]: ../reference/items/structs.html
1087 mod struct_keyword {}
1088
1089 #[doc(keyword = "super")]
1090 //
1091 /// The parent of the current [module].
1092 ///
1093 /// The documentation for this keyword is [not yet complete]. Pull requests welcome!
1094 ///
1095 /// [module]: ../reference/items/modules.html
1096 /// [not yet complete]: https://github.com/rust-lang/rust/issues/34601
1097 mod super_keyword {}
1098
1099 #[doc(keyword = "trait")]
1100 //
1101 /// A common interface for a class of types.
1102 ///
1103 /// The documentation for this keyword is [not yet complete]. Pull requests welcome!
1104 ///
1105 /// [not yet complete]: https://github.com/rust-lang/rust/issues/34601
1106 mod trait_keyword {}
1107
1108 #[doc(keyword = "true")]
1109 //
1110 /// A value of type [`bool`] representing logical **true**.
1111 ///
1112 /// Logically `true` is not equal to [`false`].
1113 ///
1114 /// ## Control structures that check for **true**
1115 ///
1116 /// Several of Rust's control structures will check for a `bool` condition evaluating to **true**.
1117 ///
1118 ///   * The condition in an [`if`] expression must be of type `bool`.
1119 ///     Whenever that condition evaluates to **true**, the `if` expression takes
1120 ///     on the value of the first block. If however, the condition evaluates
1121 ///     to `false`, the expression takes on value of the `else` block if there is one.
1122 ///
1123 ///   * [`while`] is another control flow construct expecting a `bool`-typed condition.
1124 ///     As long as the condition evaluates to **true**, the `while` loop will continually
1125 ///     evaluate its associated block.
1126 ///
1127 ///   * [`match`] arms can have guard clauses on them.
1128 ///
1129 /// [`if`]: keyword.if.html
1130 /// [`while`]: keyword.while.html
1131 /// [`match`]: ../reference/expressions/match-expr.html#match-guards
1132 /// [`false`]: keyword.false.html
1133 /// [`bool`]: primitive.bool.html
1134 mod true_keyword {}
1135
1136 #[doc(keyword = "type")]
1137 //
1138 /// Define an alias for an existing type.
1139 ///
1140 /// The documentation for this keyword is [not yet complete]. Pull requests welcome!
1141 ///
1142 /// [not yet complete]: https://github.com/rust-lang/rust/issues/34601
1143 mod type_keyword {}
1144
1145 #[doc(keyword = "unsafe")]
1146 //
1147 /// Code or interfaces whose [memory safety] cannot be verified by the type system.
1148 ///
1149 /// The documentation for this keyword is [not yet complete]. Pull requests welcome!
1150 ///
1151 /// [memory safety]: ../book/ch19-01-unsafe-rust.html
1152 /// [not yet complete]: https://github.com/rust-lang/rust/issues/34601
1153 mod unsafe_keyword {}
1154
1155 #[doc(keyword = "use")]
1156 //
1157 /// Import or rename items from other crates or modules.
1158 ///
1159 /// The documentation for this keyword is [not yet complete]. Pull requests welcome!
1160 ///
1161 /// [not yet complete]: https://github.com/rust-lang/rust/issues/34601
1162 mod use_keyword {}
1163
1164 #[doc(keyword = "where")]
1165 //
1166 /// Add constraints that must be upheld to use an item.
1167 ///
1168 /// The documentation for this keyword is [not yet complete]. Pull requests welcome!
1169 ///
1170 /// [not yet complete]: https://github.com/rust-lang/rust/issues/34601
1171 mod where_keyword {}
1172
1173 // 2018 Edition keywords
1174
1175 #[doc(keyword = "async")]
1176 //
1177 /// Return a [`Future`] instead of blocking the current thread.
1178 ///
1179 /// Use `async` in front of `fn`, `closure`, or a `block` to turn the marked code into a `Future`.
1180 /// As such the code will not be run immediately, but will only be evaluated when the returned
1181 /// future is `.await`ed.
1182 ///
1183 /// We have written an [async book] detailing async/await and trade-offs compared to using threads.
1184 ///
1185 /// ## Editions
1186 ///
1187 /// `async` is a keyword from the 2018 edition onwards.
1188 ///
1189 /// It is available for use in stable rust from version 1.39 onwards.
1190 ///
1191 /// [`Future`]: ./future/trait.Future.html
1192 /// [async book]: https://rust-lang.github.io/async-book/
1193 mod async_keyword {}
1194
1195 #[doc(keyword = "await")]
1196 //
1197 /// Suspend execution until the result of a [`Future`] is ready.
1198 ///
1199 /// `.await`ing a future will suspend the current function's execution until the `executor`
1200 /// has run the future to completion.
1201 ///
1202 /// Read the [async book] for details on how async/await and executors work.
1203 ///
1204 /// ## Editions
1205 ///
1206 /// `await` is a keyword from the 2018 edition onwards.
1207 ///
1208 /// It is available for use in stable rust from version 1.39 onwards.
1209 ///
1210 /// [`Future`]: ./future/trait.Future.html
1211 /// [async book]: https://rust-lang.github.io/async-book/
1212 mod await_keyword {}
1213
1214 #[doc(keyword = "dyn")]
1215 //
1216 /// `dyn` is a prefix of a [trait object]'s type.
1217 ///
1218 /// The `dyn` keyword is used to highlight that calls to methods on the associated `Trait`
1219 /// are dynamically dispatched. To use the trait this way, it must be 'object safe'.
1220 ///
1221 /// Unlike generic parameters or `impl Trait`, the compiler does not know the concrete type that
1222 /// is being passed. That is, the type has been [erased].
1223 /// As such, a `dyn Trait` reference contains _two_ pointers.
1224 /// One pointer goes to the data (e.g., an instance of a struct).
1225 /// Another pointer goes to a map of method call names to function pointers
1226 /// (known as a virtual method table or vtable).
1227 ///
1228 /// At run-time, when a method needs to be called on the `dyn Trait`, the vtable is consulted to get
1229 /// the function pointer and then that function pointer is called.
1230 ///
1231 /// ## Trade-offs
1232 ///
1233 /// The above indirection is the additional runtime cost of calling a function on a `dyn Trait`.
1234 /// Methods called by dynamic dispatch generally cannot be inlined by the compiler.
1235 ///
1236 /// However, `dyn Trait` is likely to produce smaller code than `impl Trait` / generic parameters as
1237 /// the method won't be duplicated for each concrete type.
1238 ///
1239 /// Read more about `object safety` and [trait object]s.
1240 ///
1241 /// [trait object]: ../book/ch17-02-trait-objects.html
1242 /// [erased]: https://en.wikipedia.org/wiki/Type_erasure
1243 mod dyn_keyword {}
1244
1245 #[doc(keyword = "union")]
1246 //
1247 /// The [Rust equivalent of a C-style union][union].
1248 ///
1249 /// The documentation for this keyword is [not yet complete]. Pull requests welcome!
1250 ///
1251 /// [union]: ../reference/items/unions.html
1252 /// [not yet complete]: https://github.com/rust-lang/rust/issues/34601
1253 mod union_keyword {}