3 /// Cast between types, or rename an import.
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
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);
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.
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`.
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.
33 /// `as` is also used to rename imports in [`use`] and [`extern crate`][`crate`] statements:
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`.
40 /// For more information on what `as` is capable of, see the [Reference].
42 /// [Reference]: ../reference/expressions/operator-expr.html#type-cast-expressions
43 /// [`crate`]: keyword.crate.html
44 /// [`use`]: keyword.use.html
45 /// [const-cast]: primitive.pointer.html#method.cast
46 /// [mut-cast]: primitive.pointer.html#method.cast-1
49 #[doc(keyword = "break")]
51 /// Exit early from a loop.
53 /// When `break` is encountered, execution of the associated loop body is
54 /// immediately terminated.
66 /// assert_eq!(last, 12);
67 /// println!("{}", last);
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.
74 /// 'outer: for i in 1..=5 {
75 /// println!("outer iteration (i): {}", i);
77 /// '_inner: for j in 1..=200 {
78 /// println!(" inner iteration (j): {}", j);
80 /// // breaks from inner loop, let's outer loop continue.
84 /// // breaks from outer loop, and directly to "Bye".
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.
98 /// let (mut a, mut b) = (1, 1);
99 /// let result = loop {
107 /// // first number in Fibonacci sequence over 10:
108 /// assert_eq!(result, 13);
109 /// println!("{}", result);
112 /// For more details consult the [Reference on "break expression"] and the [Reference on "break and
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
120 #[doc(keyword = "const")]
122 /// Compile-time constants and compile-time evaluable functions.
124 /// ## Compile-time constants
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:
132 /// const THING: u32 = 0xABAD1DEA;
134 /// let foo = 123 + THING;
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`.
142 /// [`File`]: crate::fs::File
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
149 /// const WORDS: &'static str = "hello rust!";
152 /// Thanks to static lifetime elision, you usually don't have to explicitly use `'static`:
155 /// const WORDS: &str = "hello convenience!";
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.
165 /// Constants, like statics, should always be in `SCREAMING_SNAKE_CASE`.
167 /// For more detail on `const`, see the [Rust Book] or the [Reference].
169 /// ## Compile-time evaluable functions
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
177 /// Turning a `fn` into a `const fn` has no effect on run-time uses of that function.
179 /// ## Other uses of `const`
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].
184 /// [pointer primitive]: primitive.pointer.html
186 /// ../book/ch03-01-variables-and-mutability.html#differences-between-variables-and-constants
187 /// [Reference]: ../reference/items/constant-items.html
188 /// [const-eval]: ../reference/const_eval.html
191 #[doc(keyword = "continue")]
193 /// Skip to the next iteration of a loop.
195 /// When `continue` is encountered, the current iteration is terminated, returning control to the
196 /// loop head, typically continuing with the next iteration.
199 /// // Printing odd numbers by skipping even ones
200 /// for number in 1..=10 {
201 /// if number % 2 == 0 {
204 /// println!("{}", number);
208 /// Like `break`, `continue` is normally associated with the innermost enclosing loop, but labels
209 /// may be used to specify the affected loop.
212 /// // Print Odd numbers under 30 with unit <= 5
213 /// 'tens: for ten in 0..3 {
214 /// '_units: for unit in 0..=9 {
215 /// if unit % 2 == 0 {
221 /// println!("{}", ten * 10 + unit);
226 /// See [continue expressions] from the reference for more details.
228 /// [continue expressions]: ../reference/expressions/loop-expr.html#continue-expressions
229 mod continue_keyword {}
231 #[doc(keyword = "crate")]
233 /// A Rust binary or library.
235 /// The primary use of the `crate` keyword is as a part of `extern crate` declarations, which are
236 /// used to specify a dependency on a crate external to the one it's declared in. Crates are the
237 /// fundamental compilation unit of Rust code, and can be seen as libraries or projects. More can
238 /// be read about crates in the [Reference].
241 /// extern crate rand;
242 /// extern crate my_crate as thing;
243 /// extern crate std; // implicitly added to the root of every Rust project
246 /// The `as` keyword can be used to change what the crate is referred to as in your project. If a
247 /// crate name includes a dash, it is implicitly imported with the dashes replaced by underscores.
249 /// `crate` can also be used as in conjunction with `pub` to signify that the item it's attached to
250 /// is public only to other members of the same crate it's in.
253 /// # #[allow(unused_imports)]
254 /// pub(crate) use std::io::Error as IoError;
255 /// pub(crate) enum CoolMarkerType { }
256 /// pub struct PublicThing {
257 /// pub(crate) semi_secret_thing: bool,
261 /// `crate` is also used to represent the absolute path of a module, where `crate` refers to the
262 /// root of the current crate. For instance, `crate::foo::bar` refers to the name `bar` inside the
263 /// module `foo`, from anywhere else in the same crate.
265 /// [Reference]: ../reference/items/extern-crates.html
268 #[doc(keyword = "else")]
270 /// What expression to evaluate when an [`if`] condition evaluates to [`false`].
272 /// `else` expressions are optional. When no else expressions are supplied it is assumed to evaluate
273 /// to the unit type `()`.
275 /// The type that the `else` blocks evaluate to must be compatible with the type that the `if` block
278 /// As can be seen below, `else` must be followed by either: `if`, `if let`, or a block `{}` and it
279 /// will return the value of that expression.
282 /// let result = if true == false {
284 /// } else if "something" == "other thing" {
286 /// } else if let Some(200) = "blarg".parse::<i32>().ok() {
289 /// println!("Sneaky side effect.");
290 /// "phew, nothing's broken"
294 /// Here's another example but here we do not try and return an expression:
297 /// if true == false {
298 /// println!("oh no");
299 /// } else if "something" == "other thing" {
300 /// println!("oh dear");
301 /// } else if let Some(200) = "blarg".parse::<i32>().ok() {
302 /// println!("uh oh");
304 /// println!("phew, nothing's broken");
308 /// The above is _still_ an expression but it will always evaluate to `()`.
310 /// There is possibly no limit to the number of `else` blocks that could follow an `if` expression
311 /// however if you have several then a [`match`] expression might be preferable.
313 /// Read more about control flow in the [Rust Book].
315 /// [Rust Book]: ../book/ch03-05-control-flow.html#handling-multiple-conditions-with-else-if
316 /// [`match`]: keyword.match.html
317 /// [`false`]: keyword.false.html
318 /// [`if`]: keyword.if.html
321 #[doc(keyword = "enum")]
323 /// A type that can be any one of several variants.
325 /// Enums in Rust are similar to those of other compiled languages like C, but have important
326 /// differences that make them considerably more powerful. What Rust calls enums are more commonly
327 /// known as [Algebraic Data Types][ADT] if you're coming from a functional programming background.
328 /// The important detail is that each enum variant can have data to go along with it.
332 /// enum SimpleEnum {
344 /// enum ComplexEnum {
348 /// usual_struct_stuff: bool,
353 /// enum EmptyEnum { }
356 /// The first enum shown is the usual kind of enum you'd find in a C-style language. The second
357 /// shows off a hypothetical example of something storing location data, with `Coord` being any
358 /// other type that's needed, for example a struct. The third example demonstrates the kind of
359 /// data a variant can store, ranging from nothing, to a tuple, to an anonymous struct.
361 /// Instantiating enum variants involves explicitly using the enum's name as its namespace,
362 /// followed by one of its variants. `SimpleEnum::SecondVariant` would be an example from above.
363 /// When data follows along with a variant, such as with rust's built-in [`Option`] type, the data
364 /// is added as the type describes, for example `Option::Some(123)`. The same follows with
365 /// struct-like variants, with things looking like `ComplexEnum::LotsOfThings { usual_struct_stuff:
366 /// true, blah: "hello!".to_string(), }`. Empty Enums are similar to [`!`] in that they cannot be
367 /// instantiated at all, and are used mainly to mess with the type system in interesting ways.
369 /// For more information, take a look at the [Rust Book] or the [Reference]
371 /// [ADT]: https://en.wikipedia.org/wiki/Algebraic_data_type
372 /// [Rust Book]: ../book/ch06-01-defining-an-enum.html
373 /// [Reference]: ../reference/items/enumerations.html
374 /// [`!`]: primitive.never.html
377 #[doc(keyword = "extern")]
379 /// Link to or import external code.
381 /// The `extern` keyword is used in two places in Rust. One is in conjunction with the [`crate`]
382 /// keyword to make your Rust code aware of other Rust crates in your project, i.e., `extern crate
383 /// lazy_static;`. The other use is in foreign function interfaces (FFI).
385 /// `extern` is used in two different contexts within FFI. The first is in the form of external
386 /// blocks, for declaring function interfaces that Rust code can call foreign code by.
389 /// #[link(name = "my_c_library")]
391 /// fn my_c_function(x: i32) -> bool;
395 /// This code would attempt to link with `libmy_c_library.so` on unix-like systems and
396 /// `my_c_library.dll` on Windows at runtime, and panic if it can't find something to link to. Rust
397 /// code could then use `my_c_function` as if it were any other unsafe Rust function. Working with
398 /// non-Rust languages and FFI is inherently unsafe, so wrappers are usually built around C APIs.
400 /// The mirror use case of FFI is also done via the `extern` keyword:
404 /// pub extern fn callable_from_c(x: i32) -> bool {
409 /// If compiled as a dylib, the resulting .so could then be linked to from a C library, and the
410 /// function could be used as if it was from any other library.
412 /// For more information on FFI, check the [Rust book] or the [Reference].
415 /// ../book/ch19-01-unsafe-rust.html#using-extern-functions-to-call-external-code
416 /// [Reference]: ../reference/items/external-blocks.html
417 /// [`crate`]: keyword.crate.html
418 mod extern_keyword {}
420 #[doc(keyword = "false")]
422 /// A value of type [`bool`] representing logical **false**.
424 /// `false` is the logical opposite of [`true`].
426 /// See the documentation for [`true`] for more information.
428 /// [`true`]: keyword.true.html
431 #[doc(keyword = "fn")]
433 /// A function or function pointer.
435 /// Functions are the primary way code is executed within Rust. Function blocks, usually just
436 /// called functions, can be defined in a variety of different places and be assigned many
437 /// different attributes and modifiers.
439 /// Standalone functions that just sit within a module not attached to anything else are common,
440 /// but most functions will end up being inside [`impl`] blocks, either on another type itself, or
441 /// as a trait impl for that type.
444 /// fn standalone_function() {
448 /// pub fn public_thing(argument: bool) -> String {
458 /// pub fn new() -> Self {
466 /// In addition to presenting fixed types in the form of `fn name(arg: type, ..) -> return_type`,
467 /// functions can also declare a list of type parameters along with trait bounds that they fall
471 /// fn generic_function<T: Clone>(x: T) -> (T, T, T) {
472 /// (x.clone(), x.clone(), x.clone())
475 /// fn generic_where<T>(x: T) -> T
476 /// where T: std::ops::Add<Output = T> + Copy
482 /// Declaring trait bounds in the angle brackets is functionally identical to using a `where`
483 /// clause. It's up to the programmer to decide which works better in each situation, but `where`
484 /// tends to be better when things get longer than one line.
486 /// Along with being made public via `pub`, `fn` can also have an [`extern`] added for use in
489 /// For more information on the various types of functions and how they're used, consult the [Rust
490 /// book] or the [Reference].
492 /// [`impl`]: keyword.impl.html
493 /// [`extern`]: keyword.extern.html
494 /// [Rust book]: ../book/ch03-03-how-functions-work.html
495 /// [Reference]: ../reference/items/functions.html
498 #[doc(keyword = "for")]
500 /// Iteration with [`in`], trait implementation with [`impl`], or [higher-ranked trait bounds]
503 /// The `for` keyword is used in many syntactic locations:
505 /// * `for` is used in for-in-loops (see below).
506 /// * `for` is used when implementing traits as in `impl Trait for Type` (see [`impl`] for more info
508 /// * `for` is also used for [higher-ranked trait bounds] as in `for<'a> &'a T: PartialEq<i32>`.
510 /// for-in-loops, or to be more precise, iterator loops, are a simple syntactic sugar over a common
511 /// practice within Rust, which is to loop over anything that implements [`IntoIterator`] until the
512 /// iterator returned by `.into_iter()` returns `None` (or the loop body uses `break`).
516 /// println!("{}", i * 2);
519 /// for i in std::iter::repeat(5) {
520 /// println!("turns out {} never stops being 5", i);
521 /// break; // would loop forever otherwise
524 /// 'outer: for x in 5..50 {
533 /// As shown in the example above, `for` loops (along with all other loops) can be tagged, using
534 /// similar syntax to lifetimes (only visually similar, entirely distinct in practice). Giving the
535 /// same tag to `break` breaks the tagged loop, which is useful for inner loops. It is definitely
538 /// A `for` loop expands as shown:
542 /// # let iterator = 0..2;
543 /// for loop_variable in iterator {
550 /// # let iterator = 0..2;
552 /// let mut _iter = std::iter::IntoIterator::into_iter(iterator);
554 /// match _iter.next() {
555 /// Some(loop_variable) => {
564 /// More details on the functionality shown can be seen at the [`IntoIterator`] docs.
566 /// For more information on for-loops, see the [Rust book] or the [Reference].
568 /// See also, [`loop`], [`while`].
570 /// [`in`]: keyword.in.html
571 /// [`impl`]: keyword.impl.html
572 /// [`loop`]: keyword.loop.html
573 /// [`while`]: keyword.while.html
574 /// [higher-ranked trait bounds]: ../reference/trait-bounds.html#higher-ranked-trait-bounds
576 /// ../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
577 /// [Reference]: ../reference/expressions/loop-expr.html#iterator-loops
580 #[doc(keyword = "if")]
582 /// Evaluate a block if a condition holds.
584 /// `if` is a familiar construct to most programmers, and is the main way you'll often do logic in
585 /// your code. However, unlike in most languages, `if` blocks can also act as expressions.
588 /// # let rude = true;
590 /// println!("whoops, mathematics broke");
592 /// println!("everything's fine!");
595 /// let greeting = if rude {
601 /// if let Ok(x) = "123".parse::<i32>() {
602 /// println!("{} double that and you get {}!", greeting, x * 2);
606 /// Shown above are the three typical forms an `if` block comes in. First is the usual kind of
607 /// thing you'd see in many languages, with an optional `else` block. Second uses `if` as an
608 /// expression, which is only possible if all branches return the same type. An `if` expression can
609 /// be used everywhere you'd expect. The third kind of `if` block is an `if let` block, which
610 /// behaves similarly to using a `match` expression:
613 /// if let Some(x) = Some(123) {
617 /// // something else
620 /// match Some(123) {
626 /// // something else
631 /// Each kind of `if` expression can be mixed and matched as needed.
634 /// if true == false {
635 /// println!("oh no");
636 /// } else if "something" == "other thing" {
637 /// println!("oh dear");
638 /// } else if let Some(200) = "blarg".parse::<i32>().ok() {
639 /// println!("uh oh");
641 /// println!("phew, nothing's broken");
645 /// The `if` keyword is used in one other place in Rust, namely as a part of pattern matching
646 /// itself, allowing patterns such as `Some(x) if x > 200` to be used.
648 /// For more information on `if` expressions, see the [Rust book] or the [Reference].
650 /// [Rust book]: ../book/ch03-05-control-flow.html#if-expressions
651 /// [Reference]: ../reference/expressions/if-expr.html
654 #[doc(keyword = "impl")]
656 /// Implement some functionality for a type.
658 /// The `impl` keyword is primarily used to define implementations on types. Inherent
659 /// implementations are standalone, while trait implementations are used to implement traits for
660 /// types, or other traits.
662 /// Functions and consts can both be defined in an implementation. A function defined in an
663 /// `impl` block can be standalone, meaning it would be called like `Foo::bar()`. If the function
664 /// takes `self`, `&self`, or `&mut self` as its first argument, it can also be called using
665 /// method-call syntax, a familiar feature to any object oriented programmer, like `foo.bar()`.
674 /// println!("boo! Example::boo() was called!");
677 /// fn answer(&mut self) {
678 /// self.number += 42;
681 /// fn get_number(&self) -> i32 {
687 /// fn do_thingy(&self);
690 /// impl Thingy for Example {
691 /// fn do_thingy(&self) {
692 /// println!("doing a thing! also, number is {}!", self.number);
697 /// For more information on implementations, see the [Rust book][book1] or the [Reference].
699 /// The other use of the `impl` keyword is in `impl Trait` syntax, which can be seen as a shorthand
700 /// for "a concrete type that implements this trait". Its primary use is working with closures,
701 /// which have type definitions generated at compile time that can't be simply typed out.
704 /// fn thing_returning_closure() -> impl Fn(i32) -> bool {
705 /// println!("here's a closure for you!");
706 /// |x: i32| x % 3 == 0
710 /// For more information on `impl Trait` syntax, see the [Rust book][book2].
712 /// [book1]: ../book/ch05-03-method-syntax.html
713 /// [Reference]: ../reference/items/implementations.html
714 /// [book2]: ../book/ch10-02-traits.html#returning-types-that-implement-traits
717 #[doc(keyword = "in")]
719 /// Iterate over a series of values with [`for`].
721 /// The expression immediately following `in` must implement the [`IntoIterator`] trait.
723 /// ## Literal Examples:
725 /// * `for _ in 1..3 {}` - Iterate over an exclusive range up to but excluding 3.
726 /// * `for _ in 1..=3 {}` - Iterate over an inclusive range up to and including 3.
728 /// (Read more about [range patterns])
730 /// [`IntoIterator`]: ../book/ch13-04-performance.html
731 /// [range patterns]: ../reference/patterns.html?highlight=range#range-patterns
732 /// [`for`]: keyword.for.html
735 #[doc(keyword = "let")]
737 /// Bind a value to a variable.
739 /// The primary use for the `let` keyword is in `let` statements, which are used to introduce a new
740 /// set of variables into the current scope, as given by a pattern.
743 /// # #![allow(unused_assignments)]
744 /// let thing1: i32 = 100;
745 /// let thing2 = 200 + thing1;
747 /// let mut changing_thing = true;
748 /// changing_thing = false;
750 /// let (part1, part2) = ("first", "second");
757 /// let Example { a, b: _ } = Example {
764 /// The pattern is most commonly a single variable, which means no pattern matching is done and
765 /// the expression given is bound to the variable. Apart from that, patterns used in `let` bindings
766 /// can be as complicated as needed, given that the pattern is exhaustive. See the [Rust
767 /// book][book1] for more information on pattern matching. The type of the pattern is optionally
768 /// given afterwards, but if left blank is automatically inferred by the compiler if possible.
770 /// Variables in Rust are immutable by default, and require the `mut` keyword to be made mutable.
772 /// Multiple variables can be defined with the same name, known as shadowing. This doesn't affect
773 /// the original variable in any way beyond being unable to directly access it beyond the point of
774 /// shadowing. It continues to remain in scope, getting dropped only when it falls out of scope.
775 /// Shadowed variables don't need to have the same type as the variables shadowing them.
778 /// let shadowing_example = true;
779 /// let shadowing_example = 123.4;
780 /// let shadowing_example = shadowing_example as u32;
781 /// let mut shadowing_example = format!("cool! {}", shadowing_example);
782 /// shadowing_example += " something else!"; // not shadowing
785 /// Other places the `let` keyword is used include along with [`if`], in the form of `if let`
786 /// expressions. They're useful if the pattern being matched isn't exhaustive, such as with
787 /// enumerations. `while let` also exists, which runs a loop with a pattern matched value until
788 /// that pattern can't be matched.
790 /// For more information on the `let` keyword, see the [Rust book][book2] or the [Reference]
792 /// [book1]: ../book/ch06-02-match.html
793 /// [`if`]: keyword.if.html
794 /// [book2]: ../book/ch18-01-all-the-places-for-patterns.html#let-statements
795 /// [Reference]: ../reference/statements.html#let-statements
798 #[doc(keyword = "while")]
800 /// Loop while a condition is upheld.
802 /// A `while` expression is used for predicate loops. The `while` expression runs the conditional
803 /// expression before running the loop body, then runs the loop body if the conditional
804 /// expression evaluates to `true`, or exits the loop otherwise.
807 /// let mut counter = 0;
809 /// while counter < 10 {
810 /// println!("{}", counter);
815 /// Like the [`for`] expression, we can use `break` and `continue`. A `while` expression
816 /// cannot break with a value and always evaluates to `()` unlike [`loop`].
824 /// break; // Exit when `i` is 64.
829 /// As `if` expressions have their pattern matching variant in `if let`, so too do `while`
830 /// expressions with `while let`. The `while let` expression matches the pattern against the
831 /// expression, then runs the loop body if pattern matching succeeds, or exits the loop otherwise.
832 /// We can use `break` and `continue` in `while let` expressions just like in `while`.
835 /// let mut counter = Some(0);
837 /// while let Some(i) = counter {
841 /// println!("{}", i);
842 /// counter = Some (i + 1);
847 /// For more information on `while` and loops in general, see the [reference].
849 /// See also, [`for`], [`loop`].
851 /// [`for`]: keyword.for.html
852 /// [`loop`]: keyword.loop.html
853 /// [reference]: ../reference/expressions/loop-expr.html#predicate-loops
856 #[doc(keyword = "loop")]
858 /// Loop indefinitely.
860 /// `loop` is used to define the simplest kind of loop supported in Rust. It runs the code inside
861 /// it until the code uses `break` or the program exits.
865 /// println!("hello world forever!");
871 /// println!("i is {}", i);
877 /// assert_eq!(i, 128);
880 /// Unlike the other kinds of loops in Rust (`while`, `while let`, and `for`), loops can be used as
881 /// expressions that return values via `break`.
885 /// let something = loop {
891 /// assert_eq!(something, 128);
894 /// Every `break` in a loop has to have the same type. When it's not explicitly giving something,
895 /// `break;` returns `()`.
897 /// For more information on `loop` and loops in general, see the [Reference].
899 /// See also, [`for`], [`while`].
901 /// [`for`]: keyword.for.html
902 /// [`while`]: keyword.while.html
903 /// [Reference]: ../reference/expressions/loop-expr.html
906 #[doc(keyword = "match")]
908 /// Control flow based on pattern matching.
910 /// `match` can be used to run code conditionally. Every pattern must
911 /// be handled exhaustively either explicitly or by using wildcards like
912 /// `_` in the `match`. Since `match` is an expression, values can also be
916 /// let opt = Option::None::<usize>;
917 /// let x = match opt {
918 /// Some(int) => int,
921 /// assert_eq!(x, 10);
923 /// let a_number = Option::Some(10);
925 /// Some(x) if x <= 5 => println!("0 to 5 num = {}", x),
926 /// Some(x @ 6..=10) => println!("6 to 10 num = {}", x),
927 /// None => panic!(),
928 /// // all other numbers
933 /// `match` can be used to gain access to the inner members of an enum
934 /// and use them directly.
938 /// Double(Option<u8>, Option<String>),
939 /// Single(Option<u8>),
943 /// let get_inner = Outer::Double(None, Some(String::new()));
944 /// match get_inner {
945 /// Outer::Double(None, Some(st)) => println!("{}", st),
946 /// Outer::Single(opt) => println!("{:?}", opt),
951 /// For more information on `match` and matching in general, see the [Reference].
953 /// [Reference]: ../reference/expressions/match-expr.html
956 #[doc(keyword = "mod")]
958 /// Organize code into [modules].
960 /// Use `mod` to create new [modules] to encapsulate code, including other
966 /// type MyType = (u8, u8);
972 /// Like [`struct`]s and [`enum`]s, a module and its content are private by
973 /// default, unaccessible to code outside of the module.
975 /// To learn more about allowing access, see the documentation for the [`pub`]
978 /// [`enum`]: keyword.enum.html
979 /// [`pub`]: keyword.pub.html
980 /// [`struct`]: keyword.struct.html
981 /// [modules]: ../reference/items/modules.html
984 #[doc(keyword = "move")]
986 /// Capture a [closure]'s environment by value.
988 /// `move` converts any variables captured by reference or mutable reference
989 /// to owned by value variables.
992 /// let capture = "hello";
993 /// let closure = move || {
994 /// println!("rust says {}", capture);
998 /// Note: `move` closures may still implement [`Fn`] or [`FnMut`], even though
999 /// they capture variables by `move`. This is because the traits implemented by
1000 /// a closure type are determined by *what* the closure does with captured
1001 /// values, not *how* it captures them:
1004 /// fn create_fn() -> impl Fn() {
1005 /// let text = "Fn".to_owned();
1007 /// move || println!("This is a: {}", text)
1010 /// let fn_plain = create_fn();
1015 /// `move` is often used when [threads] are involved.
1020 /// std::thread::spawn(move || {
1021 /// println!("captured {} by value", x)
1022 /// }).join().unwrap();
1024 /// // x is no longer available
1027 /// `move` is also valid before an async block.
1030 /// let capture = "hello";
1031 /// let block = async move {
1032 /// println!("rust says {} from async block", capture);
1036 /// For more information on the `move` keyword, see the [closure]'s section
1037 /// of the Rust book or the [threads] section
1039 /// [closure]: ../book/ch13-01-closures.html
1040 /// [threads]: ../book/ch16-01-threads.html#using-move-closures-with-threads
1043 #[doc(keyword = "mut")]
1045 /// A mutable variable, reference, or pointer.
1047 /// `mut` can be used in several situations. The first is mutable variables,
1048 /// which can be used anywhere you can bind a value to a variable name. Some
1052 /// // A mutable variable in the parameter list of a function.
1053 /// fn foo(mut x: u8, y: u8) -> u8 {
1058 /// // Modifying a mutable variable.
1059 /// # #[allow(unused_assignments)]
1063 /// assert_eq!(foo(3, 4), 7);
1064 /// assert_eq!(a, 6);
1067 /// The second is mutable references. They can be created from `mut` variables
1068 /// and must be unique: no other variables can have a mutable reference, nor a
1069 /// shared reference.
1072 /// // Taking a mutable reference.
1073 /// fn push_two(v: &mut Vec<u8>) {
1077 /// // A mutable reference cannot be taken to a non-mutable variable.
1078 /// let mut v = vec![0, 1];
1079 /// // Passing a mutable reference.
1080 /// push_two(&mut v);
1082 /// assert_eq!(v, vec![0, 1, 2]);
1085 /// ```rust,compile_fail,E0502
1086 /// let mut v = vec![0, 1];
1087 /// let mut_ref_v = &mut v;
1088 /// ##[allow(unused)]
1090 /// mut_ref_v.push(2);
1093 /// Mutable raw pointers work much like mutable references, with the added
1094 /// possibility of not pointing to a valid object. The syntax is `*mut Type`.
1096 /// More information on mutable references and pointers can be found in```
1099 /// [Reference]: ../reference/types/pointer.html#mutable-references-mut
1102 #[doc(keyword = "pub")]
1104 /// Make an item visible to others.
1106 /// The keyword `pub` makes any module, function, or data structure accessible from inside
1107 /// of external modules. The `pub` keyword may also be used in a `use` declaration to re-export
1108 /// an identifier from a namespace.
1110 /// For more information on the `pub` keyword, please see the visibility section
1111 /// of the [reference] and for some examples, see [Rust by Example].
1113 /// [reference]:../reference/visibility-and-privacy.html?highlight=pub#visibility-and-privacy
1114 /// [Rust by Example]:../rust-by-example/mod/visibility.html
1117 #[doc(keyword = "ref")]
1119 /// Bind by reference during pattern matching.
1121 /// `ref` annotates pattern bindings to make them borrow rather than move.
1122 /// It is **not** a part of the pattern as far as matching is concerned: it does
1123 /// not affect *whether* a value is matched, only *how* it is matched.
1125 /// By default, [`match`] statements consume all they can, which can sometimes
1126 /// be a problem, when you don't really need the value to be moved and owned:
1128 /// ```compile_fail,E0382
1129 /// let maybe_name = Some(String::from("Alice"));
1130 /// // The variable 'maybe_name' is consumed here ...
1131 /// match maybe_name {
1132 /// Some(n) => println!("Hello, {}", n),
1133 /// _ => println!("Hello, world"),
1135 /// // ... and is now unavailable.
1136 /// println!("Hello again, {}", maybe_name.unwrap_or("world".into()));
1139 /// Using the `ref` keyword, the value is only borrowed, not moved, making it
1140 /// available for use after the [`match`] statement:
1143 /// let maybe_name = Some(String::from("Alice"));
1144 /// // Using `ref`, the value is borrowed, not moved ...
1145 /// match maybe_name {
1146 /// Some(ref n) => println!("Hello, {}", n),
1147 /// _ => println!("Hello, world"),
1149 /// // ... so it's available here!
1150 /// println!("Hello again, {}", maybe_name.unwrap_or("world".into()));
1155 /// - `&` denotes that your pattern expects a reference to an object. Hence `&`
1156 /// is a part of said pattern: `&Foo` matches different objects than `Foo` does.
1158 /// - `ref` indicates that you want a reference to an unpacked value. It is not
1159 /// matched against: `Foo(ref foo)` matches the same objects as `Foo(foo)`.
1161 /// See also the [Reference] for more information.
1163 /// [`match`]: keyword.match.html
1164 /// [Reference]: ../reference/patterns.html#identifier-patterns
1167 #[doc(keyword = "return")]
1169 /// Return a value from a function.
1171 /// A `return` marks the end of an execution path in a function:
1174 /// fn foo() -> i32 {
1177 /// assert_eq!(foo(), 3);
1180 /// `return` is not needed when the returned value is the last expression in the
1181 /// function. In this case the `;` is omitted:
1184 /// fn foo() -> i32 {
1187 /// assert_eq!(foo(), 3);
1190 /// `return` returns from the function immediately (an "early return"):
1193 /// use std::fs::File;
1194 /// use std::io::{Error, ErrorKind, Read, Result};
1196 /// fn main() -> Result<()> {
1197 /// let mut file = match File::open("foo.txt") {
1199 /// Err(e) => return Err(e),
1202 /// let mut contents = String::new();
1203 /// let size = match file.read_to_string(&mut contents) {
1205 /// Err(e) => return Err(e),
1208 /// if contents.contains("impossible!") {
1209 /// return Err(Error::new(ErrorKind::Other, "oh no!"));
1212 /// if size > 9000 {
1213 /// return Err(Error::new(ErrorKind::Other, "over 9000!"));
1216 /// assert_eq!(contents, "Hello, world!");
1220 mod return_keyword {}
1222 #[doc(keyword = "self")]
1224 /// The receiver of a method, or the current module.
1226 /// `self` is used in two situations: referencing the current module and marking
1227 /// the receiver of a method.
1229 /// In paths, `self` can be used to refer to the current module, either in a
1230 /// [`use`] statement or in a path to access an element:
1233 /// # #![allow(unused_imports)]
1234 /// use std::io::{self, Read};
1237 /// Is functionally the same as:
1240 /// # #![allow(unused_imports)]
1242 /// use std::io::Read;
1245 /// Using `self` to access an element in the current module:
1248 /// # #![allow(dead_code)]
1256 /// `self` as the current receiver for a method allows to omit the parameter
1257 /// type most of the time. With the exception of this particularity, `self` is
1258 /// used much like any other parameter:
1261 /// struct Foo(i32);
1265 /// fn new() -> Self {
1269 /// // Consuming `self`.
1270 /// fn consume(self) -> Self {
1271 /// Self(self.0 + 1)
1274 /// // Borrowing `self`.
1275 /// fn borrow(&self) -> &i32 {
1279 /// // Borrowing `self` mutably.
1280 /// fn borrow_mut(&mut self) -> &mut i32 {
1285 /// // This method must be called with a `Type::` prefix.
1286 /// let foo = Foo::new();
1287 /// assert_eq!(foo.0, 0);
1289 /// // Those two calls produces the same result.
1290 /// let foo = Foo::consume(foo);
1291 /// assert_eq!(foo.0, 1);
1292 /// let foo = foo.consume();
1293 /// assert_eq!(foo.0, 2);
1295 /// // Borrowing is handled automatically with the second syntax.
1296 /// let borrow_1 = Foo::borrow(&foo);
1297 /// let borrow_2 = foo.borrow();
1298 /// assert_eq!(borrow_1, borrow_2);
1300 /// // Borrowing mutably is handled automatically too with the second syntax.
1301 /// let mut foo = Foo::new();
1302 /// *Foo::borrow_mut(&mut foo) += 1;
1303 /// assert_eq!(foo.0, 1);
1304 /// *foo.borrow_mut() += 1;
1305 /// assert_eq!(foo.0, 2);
1308 /// Note that this automatic conversion when calling `foo.method()` is not
1309 /// limited to the examples above. See the [Reference] for more information.
1311 /// [`use`]: keyword.use.html
1312 /// [Reference]: ../reference/items/associated-items.html#methods
1315 #[doc(keyword = "Self")]
1317 /// The implementing type within a [`trait`] or [`impl`] block, or the current type within a type
1320 /// Within a type definition:
1323 /// # #![allow(dead_code)]
1326 /// // `Self` is a `Node` here.
1327 /// next: Option<Box<Self>>,
1331 /// In an [`impl`] block:
1334 /// struct Foo(i32);
1337 /// fn new() -> Self {
1342 /// assert_eq!(Foo::new().0, Foo(0).0);
1345 /// Generic parameters are implicit with `Self`:
1348 /// # #![allow(dead_code)]
1349 /// struct Wrap<T> {
1353 /// impl<T> Wrap<T> {
1354 /// fn new(elem: T) -> Self {
1360 /// In a [`trait`] definition and related [`impl`] block:
1364 /// fn example() -> Self;
1367 /// struct Foo(i32);
1369 /// impl Example for Foo {
1370 /// fn example() -> Self {
1375 /// assert_eq!(Foo::example().0, Foo(42).0);
1378 /// [`impl`]: keyword.impl.html
1379 /// [`trait`]: keyword.trait.html
1380 mod self_upper_keyword {}
1382 #[doc(keyword = "static")]
1384 /// A static item is a value which is valid for the entire duration of your
1385 /// program (a `'static` lifetime).
1387 /// On the surface, `static` items seem very similar to [`const`]s: both contain
1388 /// a value, both require type annotations and both can only be initialized with
1389 /// constant functions and values. However, `static`s are notably different in
1390 /// that they represent a location in memory. That means that you can have
1391 /// references to `static` items and potentially even modify them, making them
1392 /// essentially global variables.
1394 /// Static items do not call [`drop`] at the end of the program.
1396 /// There are two types of `static` items: those declared in association with
1397 /// the [`mut`] keyword and those without.
1399 /// Static items cannot be moved:
1401 /// ```rust,compile_fail,E0507
1402 /// static VEC: Vec<u32> = vec![];
1404 /// fn move_vec(v: Vec<u32>) -> Vec<u32> {
1408 /// // This line causes an error
1412 /// # Simple `static`s
1414 /// Accessing non-[`mut`] `static` items is considered safe, but some
1415 /// restrictions apply. Most notably, the type of a `static` value needs to
1416 /// implement the [`Sync`] trait, ruling out interior mutability containers
1417 /// like [`RefCell`]. See the [Reference] for more information.
1420 /// static FOO: [i32; 5] = [1, 2, 3, 4, 5];
1422 /// let r1 = &FOO as *const _;
1423 /// let r2 = &FOO as *const _;
1424 /// // With a strictly read-only static, references will have the same address
1425 /// assert_eq!(r1, r2);
1426 /// // A static item can be used just like a variable in many cases
1427 /// println!("{:?}", FOO);
1430 /// # Mutable `static`s
1432 /// If a `static` item is declared with the [`mut`] keyword, then it is allowed
1433 /// to be modified by the program. However, accessing mutable `static`s can
1434 /// cause undefined behavior in a number of ways, for example due to data races
1435 /// in a multithreaded context. As such, all accesses to mutable `static`s
1436 /// require an [`unsafe`] block.
1438 /// Despite their unsafety, mutable `static`s are necessary in many contexts:
1439 /// they can be used to represent global state shared by the whole program or in
1440 /// [`extern`] blocks to bind to variables from C libraries.
1442 /// In an [`extern`] block:
1445 /// # #![allow(dead_code)]
1447 /// static mut ERROR_MESSAGE: *mut std::os::raw::c_char;
1451 /// Mutable `static`s, just like simple `static`s, have some restrictions that
1452 /// apply to them. See the [Reference] for more information.
1454 /// [`const`]: keyword.const.html
1455 /// [`extern`]: keyword.extern.html
1456 /// [`mut`]: keyword.mut.html
1457 /// [`unsafe`]: keyword.unsafe.html
1458 /// [`RefCell`]: cell::RefCell
1459 /// [Reference]: ../reference/items/static-items.html
1460 mod static_keyword {}
1462 #[doc(keyword = "struct")]
1464 /// A type that is composed of other types.
1466 /// Structs in Rust come in three flavors: Structs with named fields, tuple structs, and unit
1470 /// struct Regular {
1473 /// pub field3: bool
1476 /// struct Tuple(u32, String);
1481 /// Regular structs are the most commonly used. Each field defined within them has a name and a
1482 /// type, and once defined can be accessed using `example_struct.field` syntax. The fields of a
1483 /// struct share its mutability, so `foo.bar = 2;` would only be valid if `foo` was mutable. Adding
1484 /// `pub` to a field makes it visible to code in other modules, as well as allowing it to be
1485 /// directly accessed and modified.
1487 /// Tuple structs are similar to regular structs, but its fields have no names. They are used like
1488 /// tuples, with deconstruction possible via `let TupleStruct(x, y) = foo;` syntax. For accessing
1489 /// individual variables, the same syntax is used as with regular tuples, namely `foo.0`, `foo.1`,
1490 /// etc, starting at zero.
1492 /// Unit structs are most commonly used as marker. They have a size of zero bytes, but unlike empty
1493 /// enums they can be instantiated, making them isomorphic to the unit type `()`. Unit structs are
1494 /// useful when you need to implement a trait on something, but don't need to store any data inside
1499 /// Structs can be instantiated in different ways, all of which can be mixed and
1500 /// matched as needed. The most common way to make a new struct is via a constructor method such as
1501 /// `new()`, but when that isn't available (or you're writing the constructor itself), struct
1502 /// literal syntax is used:
1505 /// # struct Foo { field1: f32, field2: String, etc: bool }
1506 /// let example = Foo {
1508 /// field2: "blah".to_string(),
1513 /// It's only possible to directly instantiate a struct using struct literal syntax when all of its
1514 /// fields are visible to you.
1516 /// There are a handful of shortcuts provided to make writing constructors more convenient, most
1517 /// common of which is the Field Init shorthand. When there is a variable and a field of the same
1518 /// name, the assignment can be simplified from `field: field` into simply `field`. The following
1519 /// example of a hypothetical constructor demonstrates this:
1528 /// pub fn new(name: String) -> Self {
1537 /// Another shortcut for struct instantiation is available, used when you need to make a new
1538 /// struct that has the same values as most of a previous struct of the same type, called struct
1542 /// # struct Foo { field1: String, field2: () }
1543 /// # let thing = Foo { field1: "".to_string(), field2: () };
1544 /// let updated_thing = Foo {
1545 /// field1: "a new value".to_string(),
1550 /// Tuple structs are instantiated in the same way as tuples themselves, except with the struct's
1551 /// name as a prefix: `Foo(123, false, 0.1)`.
1553 /// Empty structs are instantiated with just their name, and don't need anything else. `let thing =
1556 /// # Style conventions
1558 /// Structs are always written in CamelCase, with few exceptions. While the trailing comma on a
1559 /// struct's list of fields can be omitted, it's usually kept for convenience in adding and
1560 /// removing fields down the line.
1562 /// For more information on structs, take a look at the [Rust Book][book] or the
1563 /// [Reference][reference].
1565 /// [`PhantomData`]: marker::PhantomData
1566 /// [book]: ../book/ch05-01-defining-structs.html
1567 /// [reference]: ../reference/items/structs.html
1568 mod struct_keyword {}
1570 #[doc(keyword = "super")]
1572 /// The parent of the current [module].
1575 /// # #![allow(dead_code)]
1582 /// super::a::foo(); // call a's foo function
1587 /// It is also possible to use `super` multiple times: `super::super::foo`,
1588 /// going up the ancestor chain.
1590 /// See the [Reference] for more information.
1592 /// [module]: ../reference/items/modules.html
1593 /// [Reference]: ../reference/paths.html#super
1594 mod super_keyword {}
1596 #[doc(keyword = "trait")]
1598 /// A common interface for a group of types.
1600 /// A `trait` is like an interface that data types can implement. When a type
1601 /// implements a trait it can be treated abstractly as that trait using generics
1602 /// or trait objects.
1604 /// Traits can be made up of three varieties of associated items:
1606 /// - functions and methods
1610 /// Traits may also contain additional type parameters. Those type parameters
1611 /// or the trait itself can be constrained by other traits.
1613 /// Traits can serve as markers or carry other logical semantics that
1614 /// aren't expressed through their items. When a type implements that
1615 /// trait it is promising to uphold its contract. [`Send`] and [`Sync`] are two
1616 /// such marker traits present in the standard library.
1618 /// See the [Reference][Ref-Traits] for a lot more information on traits.
1622 /// Traits are declared using the `trait` keyword. Types can implement them
1623 /// using [`impl`] `Trait` [`for`] `Type`:
1627 /// const ZERO: Self;
1628 /// fn is_zero(&self) -> bool;
1631 /// impl Zero for i32 {
1632 /// const ZERO: Self = 0;
1634 /// fn is_zero(&self) -> bool {
1635 /// *self == Self::ZERO
1639 /// assert_eq!(i32::ZERO, 0);
1640 /// assert!(i32::ZERO.is_zero());
1641 /// assert!(!4.is_zero());
1644 /// With an associated type:
1650 /// fn build(&self) -> Self::Built;
1654 /// Traits can be generic, with constraints or without:
1657 /// trait MaybeFrom<T> {
1658 /// fn maybe_from(value: T) -> Option<Self>
1664 /// Traits can build upon the requirements of other traits. In the example
1665 /// below `Iterator` is a **supertrait** and `ThreeIterator` is a **subtrait**:
1668 /// trait ThreeIterator: std::iter::Iterator {
1669 /// fn next_three(&mut self) -> Option<[Self::Item; 3]>;
1673 /// Traits can be used in functions, as parameters:
1676 /// # #![allow(dead_code)]
1677 /// fn debug_iter<I: Iterator>(it: I) where I::Item: std::fmt::Debug {
1678 /// for elem in it {
1679 /// println!("{:#?}", elem);
1683 /// // u8_len_1, u8_len_2 and u8_len_3 are equivalent
1685 /// fn u8_len_1(val: impl Into<Vec<u8>>) -> usize {
1686 /// val.into().len()
1689 /// fn u8_len_2<T: Into<Vec<u8>>>(val: T) -> usize {
1690 /// val.into().len()
1693 /// fn u8_len_3<T>(val: T) -> usize
1695 /// T: Into<Vec<u8>>,
1697 /// val.into().len()
1701 /// Or as return types:
1704 /// # #![allow(dead_code)]
1705 /// fn from_zero_to(v: u8) -> impl Iterator<Item = u8> {
1706 /// (0..v).into_iter()
1710 /// The use of the [`impl`] keyword in this position allows the function writer
1711 /// to hide the concrete type as an implementation detail which can change
1712 /// without breaking user's code.
1716 /// A *trait object* is an opaque value of another type that implements a set of
1717 /// traits. A trait object implements all specified traits as well as their
1718 /// supertraits (if any).
1720 /// The syntax is the following: `dyn BaseTrait + AutoTrait1 + ... AutoTraitN`.
1721 /// Only one `BaseTrait` can be used so this will not compile:
1723 /// ```rust,compile_fail,E0225
1727 /// let _: Box<dyn A + B>;
1730 /// Neither will this, which is a syntax error:
1732 /// ```rust,compile_fail
1736 /// let _: Box<dyn A + dyn B>;
1739 /// On the other hand, this is correct:
1744 /// let _: Box<dyn A + Send + Sync>;
1747 /// The [Reference][Ref-Trait-Objects] has more information about trait objects,
1748 /// their limitations and the differences between editions.
1752 /// Some traits may be unsafe to implement. Using the [`unsafe`] keyword in
1753 /// front of the trait's declaration is used to mark this:
1756 /// unsafe trait UnsafeTrait {}
1758 /// unsafe impl UnsafeTrait for i32 {}
1761 /// # Differences between the 2015 and 2018 editions
1763 /// In the 2015 edition the parameters pattern was not needed for traits:
1765 /// ```rust,edition2015
1771 /// This behavior is no longer valid in edition 2018.
1773 /// [`for`]: keyword.for.html
1774 /// [`impl`]: keyword.impl.html
1775 /// [`unsafe`]: keyword.unsafe.html
1776 /// [Ref-Traits]: ../reference/items/traits.html
1777 /// [Ref-Trait-Objects]: ../reference/types/trait-object.html
1778 mod trait_keyword {}
1780 #[doc(keyword = "true")]
1782 /// A value of type [`bool`] representing logical **true**.
1784 /// Logically `true` is not equal to [`false`].
1786 /// ## Control structures that check for **true**
1788 /// Several of Rust's control structures will check for a `bool` condition evaluating to **true**.
1790 /// * The condition in an [`if`] expression must be of type `bool`.
1791 /// Whenever that condition evaluates to **true**, the `if` expression takes
1792 /// on the value of the first block. If however, the condition evaluates
1793 /// to `false`, the expression takes on value of the `else` block if there is one.
1795 /// * [`while`] is another control flow construct expecting a `bool`-typed condition.
1796 /// As long as the condition evaluates to **true**, the `while` loop will continually
1797 /// evaluate its associated block.
1799 /// * [`match`] arms can have guard clauses on them.
1801 /// [`if`]: keyword.if.html
1802 /// [`while`]: keyword.while.html
1803 /// [`match`]: ../reference/expressions/match-expr.html#match-guards
1804 /// [`false`]: keyword.false.html
1807 #[doc(keyword = "type")]
1809 /// Define an alias for an existing type.
1811 /// The syntax is `type Name = ExistingType;`.
1815 /// `type` does **not** create a new type:
1818 /// type Meters = u32;
1819 /// type Kilograms = u32;
1821 /// let m: Meters = 3;
1822 /// let k: Kilograms = 3;
1824 /// assert_eq!(m, k);
1827 /// In traits, `type` is used to declare an [associated type]:
1830 /// trait Iterator {
1831 /// // associated type declaration
1833 /// fn next(&mut self) -> Option<Self::Item>;
1836 /// struct Once<T>(Option<T>);
1838 /// impl<T> Iterator for Once<T> {
1839 /// // associated type definition
1841 /// fn next(&mut self) -> Option<Self::Item> {
1847 /// [`trait`]: keyword.trait.html
1848 /// [associated type]: ../reference/items/associated-items.html#associated-types
1851 #[doc(keyword = "unsafe")]
1853 /// Code or interfaces whose [memory safety] cannot be verified by the type
1856 /// The `unsafe` keyword has two uses: to declare the existence of contracts the
1857 /// compiler can't check (`unsafe fn` and `unsafe trait`), and to declare that a
1858 /// programmer has checked that these contracts have been upheld (`unsafe {}`
1859 /// and `unsafe impl`, but also `unsafe fn` -- see below). They are not mutually
1860 /// exclusive, as can be seen in `unsafe fn`.
1862 /// # Unsafe abilities
1864 /// **No matter what, Safe Rust can't cause Undefined Behavior**. This is
1865 /// referred to as [soundness]: a well-typed program actually has the desired
1866 /// properties. The [Nomicon][nomicon-soundness] has a more detailed explanation
1869 /// To ensure soundness, Safe Rust is restricted enough that it can be
1870 /// automatically checked. Sometimes, however, it is necessary to write code
1871 /// that is correct for reasons which are too clever for the compiler to
1872 /// understand. In those cases, you need to use Unsafe Rust.
1874 /// Here are the abilities Unsafe Rust has in addition to Safe Rust:
1876 /// - Dereference [raw pointers]
1877 /// - Implement `unsafe` [`trait`]s
1878 /// - Call `unsafe` functions
1879 /// - Mutate [`static`]s (including [`extern`]al ones)
1880 /// - Access fields of [`union`]s
1882 /// However, this extra power comes with extra responsibilities: it is now up to
1883 /// you to ensure soundness. The `unsafe` keyword helps by clearly marking the
1884 /// pieces of code that need to worry about this.
1886 /// ## The different meanings of `unsafe`
1888 /// Not all uses of `unsafe` are equivalent: some are here to mark the existence
1889 /// of a contract the programmer must check, others are to say "I have checked
1890 /// the contract, go ahead and do this". The following
1891 /// [discussion on Rust Internals] has more in-depth explanations about this but
1892 /// here is a summary of the main points:
1894 /// - `unsafe fn`: calling this function means abiding by a contract the
1895 /// compiler cannot enforce.
1896 /// - `unsafe trait`: implementing the [`trait`] means abiding by a
1897 /// contract the compiler cannot enforce.
1898 /// - `unsafe {}`: the contract necessary to call the operations inside the
1899 /// block has been checked by the programmer and is guaranteed to be respected.
1900 /// - `unsafe impl`: the contract necessary to implement the trait has been
1901 /// checked by the programmer and is guaranteed to be respected.
1903 /// `unsafe fn` also acts like an `unsafe {}` block
1904 /// around the code inside the function. This means it is not just a signal to
1905 /// the caller, but also promises that the preconditions for the operations
1906 /// inside the function are upheld. Mixing these two meanings can be confusing
1907 /// and [proposal]s exist to use `unsafe {}` blocks inside such functions when
1908 /// making `unsafe` operations.
1910 /// See the [Rustnomicon] and the [Reference] for more informations.
1914 /// ## Marking elements as `unsafe`
1916 /// `unsafe` can be used on functions. Note that functions and statics declared
1917 /// in [`extern`] blocks are implicitly marked as `unsafe` (but not functions
1918 /// declared as `extern "something" fn ...`). Mutable statics are always unsafe,
1919 /// wherever they are declared. Methods can also be declared as `unsafe`:
1922 /// # #![allow(dead_code)]
1923 /// static mut FOO: &str = "hello";
1925 /// unsafe fn unsafe_fn() {}
1928 /// fn unsafe_extern_fn();
1929 /// static BAR: *mut u32;
1932 /// trait SafeTraitWithUnsafeMethod {
1933 /// unsafe fn unsafe_method(&self);
1939 /// unsafe fn unsafe_method_on_struct() {}
1943 /// Traits can also be declared as `unsafe`:
1946 /// unsafe trait UnsafeTrait {}
1949 /// Since `unsafe fn` and `unsafe trait` indicate that there is a safety
1950 /// contract that the compiler cannot enforce, documenting it is important. The
1951 /// standard library has many examples of this, like the following which is an
1952 /// extract from [`Vec::set_len`]. The `# Safety` section explains the contract
1953 /// that must be fulfilled to safely call the function.
1955 /// ```rust,ignore (stub-to-show-doc-example)
1956 /// /// Forces the length of the vector to `new_len`.
1958 /// /// This is a low-level operation that maintains none of the normal
1959 /// /// invariants of the type. Normally changing the length of a vector
1960 /// /// is done using one of the safe operations instead, such as
1961 /// /// `truncate`, `resize`, `extend`, or `clear`.
1965 /// /// - `new_len` must be less than or equal to `capacity()`.
1966 /// /// - The elements at `old_len..new_len` must be initialized.
1967 /// pub unsafe fn set_len(&mut self, new_len: usize)
1970 /// ## Using `unsafe {}` blocks and `impl`s
1972 /// Performing `unsafe` operations requires an `unsafe {}` block:
1975 /// # #![allow(dead_code)]
1976 /// /// Dereference the given pointer.
1980 /// /// `ptr` must be aligned and must not be dangling.
1981 /// unsafe fn deref_unchecked(ptr: *const i32) -> i32 {
1986 /// let b = &a as *const _;
1987 /// // SAFETY: `a` has not been dropped and references are always aligned,
1988 /// // so `b` is a valid address.
1989 /// unsafe { assert_eq!(*b, deref_unchecked(b)); };
1992 /// Traits marked as `unsafe` must be [`impl`]emented using `unsafe impl`. This
1993 /// makes a guarantee to other `unsafe` code that the implementation satisfies
1994 /// the trait's safety contract. The [Send] and [Sync] traits are examples of
1995 /// this behaviour in the standard library.
1998 /// /// Implementors of this trait must guarantee an element is always
1999 /// /// accessible with index 3.
2000 /// unsafe trait ThreeIndexable<T> {
2001 /// /// Returns a reference to the element with index 3 in `&self`.
2002 /// fn three(&self) -> &T;
2005 /// // The implementation of `ThreeIndexable` for `[T; 4]` is `unsafe`
2006 /// // because the implementor must abide by a contract the compiler cannot
2007 /// // check but as a programmer we know there will always be a valid element
2008 /// // at index 3 to access.
2009 /// unsafe impl<T> ThreeIndexable<T> for [T; 4] {
2010 /// fn three(&self) -> &T {
2011 /// // SAFETY: implementing the trait means there always is an element
2012 /// // with index 3 accessible.
2013 /// unsafe { self.get_unchecked(3) }
2017 /// let a = [1, 2, 4, 8];
2018 /// assert_eq!(a.three(), &8);
2021 /// [`extern`]: keyword.extern.html
2022 /// [`trait`]: keyword.trait.html
2023 /// [`static`]: keyword.static.html
2024 /// [`union`]: keyword.union.html
2025 /// [`impl`]: keyword.impl.html
2026 /// [raw pointers]: ../reference/types/pointer.html
2027 /// [memory safety]: ../book/ch19-01-unsafe-rust.html
2028 /// [Rustnomicon]: ../nomicon/index.html
2029 /// [nomicon-soundness]: ../nomicon/safe-unsafe-meaning.html
2030 /// [soundness]: https://rust-lang.github.io/unsafe-code-guidelines/glossary.html#soundness-of-code--of-a-library
2031 /// [Reference]: ../reference/unsafety.html
2032 /// [proposal]: https://github.com/rust-lang/rfcs/pull/2585
2033 /// [discussion on Rust Internals]: https://internals.rust-lang.org/t/what-does-unsafe-mean/6696
2034 mod unsafe_keyword {}
2036 #[doc(keyword = "use")]
2038 /// Import or rename items from other crates or modules.
2040 /// Usually a `use` keyword is used to shorten the path required to refer to a module item.
2041 /// The keyword may appear in modules, blocks and even functions, usually at the top.
2043 /// The most basic usage of the keyword is `use path::to::item;`,
2044 /// though a number of convenient shortcuts are supported:
2046 /// * Simultaneously binding a list of paths with a common prefix,
2047 /// using the glob-like brace syntax `use a::b::{c, d, e::f, g::h::i};`
2048 /// * Simultaneously binding a list of paths with a common prefix and their common parent module,
2049 /// using the [`self`] keyword, such as `use a::b::{self, c, d::e};`
2050 /// * Rebinding the target name as a new local name, using the syntax `use p::q::r as x;`.
2051 /// This can also be used with the last two features: `use a::b::{self as ab, c as abc}`.
2052 /// * Binding all paths matching a given prefix,
2053 /// using the asterisk wildcard syntax `use a::b::*;`.
2054 /// * Nesting groups of the previous features multiple times,
2055 /// such as `use a::b::{self as ab, c, d::{*, e::f}};`
2056 /// * Reexporting with visibility modifiers such as `pub use a::b;`
2057 /// * Importing with `_` to only import the methods of a trait without binding it to a name
2058 /// (to avoid conflict for example): `use ::std::io::Read as _;`.
2060 /// Using path qualifiers like [`crate`], [`super`] or [`self`] is supported: `use crate::a::b;`.
2062 /// Note that when the wildcard `*` is used on a type, it does not import its methods (though
2063 /// for `enum`s it imports the variants, as shown in the example below).
2065 /// ```compile_fail,edition2018
2066 /// enum ExampleEnum {
2071 /// impl ExampleEnum {
2072 /// fn new() -> Self {
2077 /// use ExampleEnum::*;
2080 /// let _ = VariantA;
2082 /// // Does not compile !
2086 /// For more information on `use` and paths in general, see the [Reference].
2088 /// The differences about paths and the `use` keyword between the 2015 and 2018 editions
2089 /// can also be found in the [Reference].
2091 /// [`crate`]: keyword.crate.html
2092 /// [`self`]: keyword.self.html
2093 /// [`super`]: keyword.super.html
2094 /// [Reference]: ../reference/items/use-declarations.html
2097 #[doc(keyword = "where")]
2099 /// Add constraints that must be upheld to use an item.
2101 /// `where` allows specifying constraints on lifetime and generic parameters.
2102 /// The [RFC] introducing `where` contains detailed informations about the
2107 /// `where` can be used for constraints with traits:
2110 /// fn new<T: Default>() -> T {
2114 /// fn new_where<T>() -> T
2121 /// assert_eq!(0.0, new());
2122 /// assert_eq!(0.0, new_where());
2124 /// assert_eq!(0, new());
2125 /// assert_eq!(0, new_where());
2128 /// `where` can also be used for lifetimes.
2130 /// This compiles because `longer` outlives `shorter`, thus the constraint is
2134 /// fn select<'short, 'long>(s1: &'short str, s2: &'long str, second: bool) -> &'short str
2138 /// if second { s2 } else { s1 }
2141 /// let outer = String::from("Long living ref");
2142 /// let longer = &outer;
2144 /// let inner = String::from("Short living ref");
2145 /// let shorter = &inner;
2147 /// assert_eq!(select(shorter, longer, false), shorter);
2148 /// assert_eq!(select(shorter, longer, true), longer);
2152 /// On the other hand, this will not compile because the `where 'b: 'a` clause
2153 /// is missing: the `'b` lifetime is not known to live at least as long as `'a`
2154 /// which means this function cannot ensure it always returns a valid reference:
2156 /// ```rust,compile_fail,E0623
2157 /// fn select<'a, 'b>(s1: &'a str, s2: &'b str, second: bool) -> &'a str
2159 /// if second { s2 } else { s1 }
2163 /// `where` can also be used to express more complicated constraints that cannot
2164 /// be written with the `<T: Trait>` syntax:
2167 /// fn first_or_default<I>(mut i: I) -> I::Item
2170 /// I::Item: Default,
2172 /// i.next().unwrap_or_else(I::Item::default)
2175 /// assert_eq!(first_or_default(vec![1, 2, 3].into_iter()), 1);
2176 /// assert_eq!(first_or_default(Vec::<i32>::new().into_iter()), 0);
2179 /// `where` is available anywhere generic and lifetime parameters are available,
2180 /// as can be seen with the [`Cow`](crate::borrow::Cow) type from the standard
2184 /// # #![allow(dead_code)]
2185 /// pub enum Cow<'a, B>
2187 /// B: 'a + ToOwned + ?Sized,
2189 /// Borrowed(&'a B),
2190 /// Owned(<B as ToOwned>::Owned),
2194 /// [RFC]: https://github.com/rust-lang/rfcs/blob/master/text/0135-where.md
2195 mod where_keyword {}
2197 // 2018 Edition keywords
2199 #[doc(alias = "promise")]
2200 #[doc(keyword = "async")]
2202 /// Return a [`Future`] instead of blocking the current thread.
2204 /// Use `async` in front of `fn`, `closure`, or a `block` to turn the marked code into a `Future`.
2205 /// As such the code will not be run immediately, but will only be evaluated when the returned
2206 /// future is `.await`ed.
2208 /// We have written an [async book] detailing async/await and trade-offs compared to using threads.
2212 /// `async` is a keyword from the 2018 edition onwards.
2214 /// It is available for use in stable rust from version 1.39 onwards.
2216 /// [`Future`]: future::Future
2217 /// [async book]: https://rust-lang.github.io/async-book/
2218 mod async_keyword {}
2220 #[doc(keyword = "await")]
2222 /// Suspend execution until the result of a [`Future`] is ready.
2224 /// `.await`ing a future will suspend the current function's execution until the `executor`
2225 /// has run the future to completion.
2227 /// Read the [async book] for details on how async/await and executors work.
2231 /// `await` is a keyword from the 2018 edition onwards.
2233 /// It is available for use in stable rust from version 1.39 onwards.
2235 /// [`Future`]: future::Future
2236 /// [async book]: https://rust-lang.github.io/async-book/
2237 mod await_keyword {}
2239 #[doc(keyword = "dyn")]
2241 /// `dyn` is a prefix of a [trait object]'s type.
2243 /// The `dyn` keyword is used to highlight that calls to methods on the associated `Trait`
2244 /// are dynamically dispatched. To use the trait this way, it must be 'object safe'.
2246 /// Unlike generic parameters or `impl Trait`, the compiler does not know the concrete type that
2247 /// is being passed. That is, the type has been [erased].
2248 /// As such, a `dyn Trait` reference contains _two_ pointers.
2249 /// One pointer goes to the data (e.g., an instance of a struct).
2250 /// Another pointer goes to a map of method call names to function pointers
2251 /// (known as a virtual method table or vtable).
2253 /// At run-time, when a method needs to be called on the `dyn Trait`, the vtable is consulted to get
2254 /// the function pointer and then that function pointer is called.
2258 /// The above indirection is the additional runtime cost of calling a function on a `dyn Trait`.
2259 /// Methods called by dynamic dispatch generally cannot be inlined by the compiler.
2261 /// However, `dyn Trait` is likely to produce smaller code than `impl Trait` / generic parameters as
2262 /// the method won't be duplicated for each concrete type.
2264 /// Read more about `object safety` and [trait object]s.
2266 /// [trait object]: ../book/ch17-02-trait-objects.html
2267 /// [erased]: https://en.wikipedia.org/wiki/Type_erasure
2270 #[doc(keyword = "union")]
2272 /// The [Rust equivalent of a C-style union][union].
2274 /// A `union` looks like a [`struct`] in terms of declaration, but all of its
2275 /// fields exist in the same memory, superimposed over one another. For instance,
2276 /// if we wanted some bits in memory that we sometimes interpret as a `u32` and
2277 /// sometimes as an `f32`, we could write:
2280 /// union IntOrFloat {
2285 /// let mut u = IntOrFloat { f: 1.0 };
2286 /// // Reading the fields of an union is always unsafe
2287 /// assert_eq!(unsafe { u.i }, 1065353216);
2288 /// // Updating through any of the field will modify all of them
2289 /// u.i = 1073741824;
2290 /// assert_eq!(unsafe { u.f }, 2.0);
2293 /// # Matching on unions
2295 /// It is possible to use pattern matching on `union`s. A single field name must
2296 /// be used and it must match the name of one of the `union`'s field.
2297 /// Like reading from a `union`, pattern matching on a `union` requires `unsafe`.
2300 /// union IntOrFloat {
2305 /// let u = IntOrFloat { f: 1.0 };
2309 /// IntOrFloat { i: 10 } => println!("Found exactly ten!"),
2310 /// // Matching the field `f` provides an `f32`.
2311 /// IntOrFloat { f } => println!("Found f = {} !", f),
2316 /// # References to union fields
2318 /// All fields in a `union` are all at the same place in memory which means
2319 /// borrowing one borrows the entire `union`, for the same lifetime:
2321 /// ```rust,compile_fail,E0502
2322 /// union IntOrFloat {
2327 /// let mut u = IntOrFloat { f: 1.0 };
2329 /// let f = unsafe { &u.f };
2330 /// // This will not compile because the field has already been borrowed, even
2331 /// // if only immutably
2332 /// let i = unsafe { &mut u.i };
2335 /// println!("f = {} and i = {}", f, i);
2338 /// See the [Reference][union] for more informations on `union`s.
2340 /// [`struct`]: keyword.struct.html
2341 /// [union]: ../reference/items/unions.html
2342 mod union_keyword {}