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 /// Other places `as` is used include as extra syntax for [`crate`] and `use`, to change the name
24 /// something is imported as.
26 /// For more information on what `as` is capable of, see the [Reference]
28 /// [Reference]: ../reference/expressions/operator-expr.html#type-cast-expressions
29 /// [`crate`]: keyword.crate.html
32 #[doc(keyword = "break")]
34 /// Exit early from a loop.
36 /// When `break` is encountered, execution of the associated loop body is
37 /// immediately terminated.
49 /// assert_eq!(last, 12);
50 /// println!("{}", last);
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.
57 /// 'outer: for i in 1..=5 {
58 /// println!("outer iteration (i): {}", i);
60 /// '_inner: for j in 1..=200 {
61 /// println!(" inner iteration (j): {}", j);
63 /// // breaks from inner loop, let's outer loop continue.
67 /// // breaks from outer loop, and directly to "Bye".
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.
81 /// let (mut a, mut b) = (1, 1);
82 /// let result = loop {
90 /// // first number in Fibonacci sequence over 10:
91 /// assert_eq!(result, 13);
92 /// println!("{}", result);
95 /// For more details consult the [Reference on "break expression"] and the [Reference on "break and
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
103 #[doc(keyword = "const")]
105 /// Compile-time constants and compile-time evaluable functions.
107 /// ## Compile-time constants
109 /// Sometimes a certain value is used many times throughout a program, and it can become
110 /// inconvenient to copy it over and over. What's more, it's not always possible or desirable to
111 /// make it a variable that gets carried around to each function that needs it. In these cases, the
112 /// `const` keyword provides a convenient alternative to code duplication:
115 /// const THING: u32 = 0xABAD1DEA;
117 /// let foo = 123 + THING;
120 /// Constants must be explicitly typed; unlike with `let`, you can't ignore their type and let the
121 /// compiler figure it out. Any constant value can be defined in a `const`, which in practice happens
122 /// to be most things that would be reasonable to have in a constant (barring `const fn`s). For
123 /// example, you can't have a [`File`] as a `const`.
125 /// [`File`]: crate::fs::File
127 /// The only lifetime allowed in a constant is `'static`, which is the lifetime that encompasses
128 /// all others in a Rust program. For example, if you wanted to define a constant string, it would
132 /// const WORDS: &'static str = "hello rust!";
135 /// Thanks to static lifetime elision, you usually don't have to explicitly use `'static`:
138 /// const WORDS: &str = "hello convenience!";
141 /// `const` items looks remarkably similar to `static` items, which introduces some confusion as
142 /// to which one should be used at which times. To put it simply, constants are inlined wherever
143 /// they're used, making using them identical to simply replacing the name of the `const` with its
144 /// value. Static variables, on the other hand, point to a single location in memory, which all
145 /// accesses share. This means that, unlike with constants, they can't have destructors, and act as
146 /// a single value across the entire codebase.
148 /// Constants, like statics, should always be in `SCREAMING_SNAKE_CASE`.
150 /// For more detail on `const`, see the [Rust Book] or the [Reference].
152 /// ## Compile-time evaluable functions
154 /// The other main use of the `const` keyword is in `const fn`. This marks a function as being
155 /// callable in the body of a `const` or `static` item and in array initializers (commonly called
156 /// "const contexts"). `const fn` are restricted in the set of operations they can perform, to
157 /// ensure that they can be evaluated at compile-time. See the [Reference][const-eval] for more
160 /// Turning a `fn` into a `const fn` has no effect on run-time uses of that function.
162 /// ## Other uses of `const`
164 /// The `const` keyword is also used in raw pointers in combination with `mut`, as seen in `*const
165 /// T` and `*mut T`. More about `const` as used in raw pointers can be read at the Rust docs for the [pointer primitive].
167 /// [pointer primitive]: primitive.pointer.html
169 /// ../book/ch03-01-variables-and-mutability.html#differences-between-variables-and-constants
170 /// [Reference]: ../reference/items/constant-items.html
171 /// [const-eval]: ../reference/const_eval.html
174 #[doc(keyword = "continue")]
176 /// Skip to the next iteration of a loop.
178 /// When `continue` is encountered, the current iteration is terminated, returning control to the
179 /// loop head, typically continuing with the next iteration.
182 /// // Printing odd numbers by skipping even ones
183 /// for number in 1..=10 {
184 /// if number % 2 == 0 {
187 /// println!("{}", number);
191 /// Like `break`, `continue` is normally associated with the innermost enclosing loop, but labels
192 /// may be used to specify the affected loop.
195 /// // Print Odd numbers under 30 with unit <= 5
196 /// 'tens: for ten in 0..3 {
197 /// '_units: for unit in 0..=9 {
198 /// if unit % 2 == 0 {
204 /// println!("{}", ten * 10 + unit);
209 /// See [continue expressions] from the reference for more details.
211 /// [continue expressions]: ../reference/expressions/loop-expr.html#continue-expressions
212 mod continue_keyword {}
214 #[doc(keyword = "crate")]
216 /// A Rust binary or library.
218 /// The primary use of the `crate` keyword is as a part of `extern crate` declarations, which are
219 /// used to specify a dependency on a crate external to the one it's declared in. Crates are the
220 /// fundamental compilation unit of Rust code, and can be seen as libraries or projects. More can
221 /// be read about crates in the [Reference].
224 /// extern crate rand;
225 /// extern crate my_crate as thing;
226 /// extern crate std; // implicitly added to the root of every Rust project
229 /// The `as` keyword can be used to change what the crate is referred to as in your project. If a
230 /// crate name includes a dash, it is implicitly imported with the dashes replaced by underscores.
232 /// `crate` can also be used as in conjunction with `pub` to signify that the item it's attached to
233 /// is public only to other members of the same crate it's in.
236 /// # #[allow(unused_imports)]
237 /// pub(crate) use std::io::Error as IoError;
238 /// pub(crate) enum CoolMarkerType { }
239 /// pub struct PublicThing {
240 /// pub(crate) semi_secret_thing: bool,
244 /// `crate` is also used to represent the absolute path of a module, where `crate` refers to the
245 /// root of the current crate. For instance, `crate::foo::bar` refers to the name `bar` inside the
246 /// module `foo`, from anywhere else in the same crate.
248 /// [Reference]: ../reference/items/extern-crates.html
251 #[doc(keyword = "else")]
253 /// What expression to evaluate when an [`if`] condition evaluates to [`false`].
255 /// `else` expressions are optional. When no else expressions are supplied it is assumed to evaluate
256 /// to the unit type `()`.
258 /// The type that the `else` blocks evaluate to must be compatible with the type that the `if` block
261 /// As can be seen below, `else` must be followed by either: `if`, `if let`, or a block `{}` and it
262 /// will return the value of that expression.
265 /// let result = if true == false {
267 /// } else if "something" == "other thing" {
269 /// } else if let Some(200) = "blarg".parse::<i32>().ok() {
272 /// println!("Sneaky side effect.");
273 /// "phew, nothing's broken"
277 /// Here's another example but here we do not try and return an expression:
280 /// if true == false {
281 /// println!("oh no");
282 /// } else if "something" == "other thing" {
283 /// println!("oh dear");
284 /// } else if let Some(200) = "blarg".parse::<i32>().ok() {
285 /// println!("uh oh");
287 /// println!("phew, nothing's broken");
291 /// The above is _still_ an expression but it will always evaluate to `()`.
293 /// There is possibly no limit to the number of `else` blocks that could follow an `if` expression
294 /// however if you have several then a [`match`] expression might be preferable.
296 /// Read more about control flow in the [Rust Book].
298 /// [Rust Book]: ../book/ch03-05-control-flow.html#handling-multiple-conditions-with-else-if
299 /// [`match`]: keyword.match.html
300 /// [`false`]: keyword.false.html
301 /// [`if`]: keyword.if.html
304 #[doc(keyword = "enum")]
306 /// A type that can be any one of several variants.
308 /// Enums in Rust are similar to those of other compiled languages like C, but have important
309 /// differences that make them considerably more powerful. What Rust calls enums are more commonly
310 /// known as [Algebraic Data Types][ADT] if you're coming from a functional programming background.
311 /// The important detail is that each enum variant can have data to go along with it.
315 /// enum SimpleEnum {
327 /// enum ComplexEnum {
331 /// usual_struct_stuff: bool,
336 /// enum EmptyEnum { }
339 /// The first enum shown is the usual kind of enum you'd find in a C-style language. The second
340 /// shows off a hypothetical example of something storing location data, with `Coord` being any
341 /// other type that's needed, for example a struct. The third example demonstrates the kind of
342 /// data a variant can store, ranging from nothing, to a tuple, to an anonymous struct.
344 /// Instantiating enum variants involves explicitly using the enum's name as its namespace,
345 /// followed by one of its variants. `SimpleEnum::SecondVariant` would be an example from above.
346 /// When data follows along with a variant, such as with rust's built-in [`Option`] type, the data
347 /// is added as the type describes, for example `Option::Some(123)`. The same follows with
348 /// struct-like variants, with things looking like `ComplexEnum::LotsOfThings { usual_struct_stuff:
349 /// true, blah: "hello!".to_string(), }`. Empty Enums are similar to [`!`] in that they cannot be
350 /// instantiated at all, and are used mainly to mess with the type system in interesting ways.
352 /// For more information, take a look at the [Rust Book] or the [Reference]
354 /// [ADT]: https://en.wikipedia.org/wiki/Algebraic_data_type
355 /// [Rust Book]: ../book/ch06-01-defining-an-enum.html
356 /// [Reference]: ../reference/items/enumerations.html
357 /// [`!`]: primitive.never.html
360 #[doc(keyword = "extern")]
362 /// Link to or import external code.
364 /// The `extern` keyword is used in two places in Rust. One is in conjunction with the [`crate`]
365 /// keyword to make your Rust code aware of other Rust crates in your project, i.e., `extern crate
366 /// lazy_static;`. The other use is in foreign function interfaces (FFI).
368 /// `extern` is used in two different contexts within FFI. The first is in the form of external
369 /// blocks, for declaring function interfaces that Rust code can call foreign code by.
372 /// #[link(name = "my_c_library")]
374 /// fn my_c_function(x: i32) -> bool;
378 /// This code would attempt to link with `libmy_c_library.so` on unix-like systems and
379 /// `my_c_library.dll` on Windows at runtime, and panic if it can't find something to link to. Rust
380 /// code could then use `my_c_function` as if it were any other unsafe Rust function. Working with
381 /// non-Rust languages and FFI is inherently unsafe, so wrappers are usually built around C APIs.
383 /// The mirror use case of FFI is also done via the `extern` keyword:
387 /// pub extern fn callable_from_c(x: i32) -> bool {
392 /// If compiled as a dylib, the resulting .so could then be linked to from a C library, and the
393 /// function could be used as if it was from any other library.
395 /// For more information on FFI, check the [Rust book] or the [Reference].
398 /// ../book/ch19-01-unsafe-rust.html#using-extern-functions-to-call-external-code
399 /// [Reference]: ../reference/items/external-blocks.html
400 mod extern_keyword {}
402 #[doc(keyword = "false")]
404 /// A value of type [`bool`] representing logical **false**.
406 /// `false` is the logical opposite of [`true`].
408 /// See the documentation for [`true`] for more information.
410 /// [`true`]: keyword.true.html
413 #[doc(keyword = "fn")]
415 /// A function or function pointer.
417 /// Functions are the primary way code is executed within Rust. Function blocks, usually just
418 /// called functions, can be defined in a variety of different places and be assigned many
419 /// different attributes and modifiers.
421 /// Standalone functions that just sit within a module not attached to anything else are common,
422 /// but most functions will end up being inside [`impl`] blocks, either on another type itself, or
423 /// as a trait impl for that type.
426 /// fn standalone_function() {
430 /// pub fn public_thing(argument: bool) -> String {
440 /// pub fn new() -> Self {
448 /// In addition to presenting fixed types in the form of `fn name(arg: type, ..) -> return_type`,
449 /// functions can also declare a list of type parameters along with trait bounds that they fall
453 /// fn generic_function<T: Clone>(x: T) -> (T, T, T) {
454 /// (x.clone(), x.clone(), x.clone())
457 /// fn generic_where<T>(x: T) -> T
458 /// where T: std::ops::Add<Output = T> + Copy
464 /// Declaring trait bounds in the angle brackets is functionally identical to using a `where`
465 /// clause. It's up to the programmer to decide which works better in each situation, but `where`
466 /// tends to be better when things get longer than one line.
468 /// Along with being made public via `pub`, `fn` can also have an [`extern`] added for use in
471 /// For more information on the various types of functions and how they're used, consult the [Rust
472 /// book] or the [Reference].
474 /// [`impl`]: keyword.impl.html
475 /// [`extern`]: keyword.extern.html
476 /// [Rust book]: ../book/ch03-03-how-functions-work.html
477 /// [Reference]: ../reference/items/functions.html
480 #[doc(keyword = "for")]
482 /// Iteration with [`in`], trait implementation with [`impl`], or [higher-ranked trait bounds]
485 /// The `for` keyword is used in many syntactic locations:
487 /// * `for` is used in for-in-loops (see below).
488 /// * `for` is used when implementing traits as in `impl Trait for Type` (see [`impl`] for more info
490 /// * `for` is also used for [higher-ranked trait bounds] as in `for<'a> &'a T: PartialEq<i32>`.
492 /// for-in-loops, or to be more precise, iterator loops, are a simple syntactic sugar over a common
493 /// practice within Rust, which is to loop over anything that implements [`IntoIterator`] until the
494 /// iterator returned by `.into_iter()` returns `None` (or the loop body uses `break`).
498 /// println!("{}", i * 2);
501 /// for i in std::iter::repeat(5) {
502 /// println!("turns out {} never stops being 5", i);
503 /// break; // would loop forever otherwise
506 /// 'outer: for x in 5..50 {
515 /// As shown in the example above, `for` loops (along with all other loops) can be tagged, using
516 /// similar syntax to lifetimes (only visually similar, entirely distinct in practice). Giving the
517 /// same tag to `break` breaks the tagged loop, which is useful for inner loops. It is definitely
520 /// A `for` loop expands as shown:
524 /// # let iterator = 0..2;
525 /// for loop_variable in iterator {
532 /// # let iterator = 0..2;
534 /// let mut _iter = std::iter::IntoIterator::into_iter(iterator);
536 /// match _iter.next() {
537 /// Some(loop_variable) => {
546 /// More details on the functionality shown can be seen at the [`IntoIterator`] docs.
548 /// For more information on for-loops, see the [Rust book] or the [Reference].
550 /// [`in`]: keyword.in.html
551 /// [`impl`]: keyword.impl.html
552 /// [higher-ranked trait bounds]: ../reference/trait-bounds.html#higher-ranked-trait-bounds
554 /// ../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
555 /// [Reference]: ../reference/expressions/loop-expr.html#iterator-loops
558 #[doc(keyword = "if")]
560 /// Evaluate a block if a condition holds.
562 /// `if` is a familiar construct to most programmers, and is the main way you'll often do logic in
563 /// your code. However, unlike in most languages, `if` blocks can also act as expressions.
566 /// # let rude = true;
568 /// println!("whoops, mathematics broke");
570 /// println!("everything's fine!");
573 /// let greeting = if rude {
579 /// if let Ok(x) = "123".parse::<i32>() {
580 /// println!("{} double that and you get {}!", greeting, x * 2);
584 /// Shown above are the three typical forms an `if` block comes in. First is the usual kind of
585 /// thing you'd see in many languages, with an optional `else` block. Second uses `if` as an
586 /// expression, which is only possible if all branches return the same type. An `if` expression can
587 /// be used everywhere you'd expect. The third kind of `if` block is an `if let` block, which
588 /// behaves similarly to using a `match` expression:
591 /// if let Some(x) = Some(123) {
595 /// // something else
598 /// match Some(123) {
604 /// // something else
609 /// Each kind of `if` expression can be mixed and matched as needed.
612 /// if true == false {
613 /// println!("oh no");
614 /// } else if "something" == "other thing" {
615 /// println!("oh dear");
616 /// } else if let Some(200) = "blarg".parse::<i32>().ok() {
617 /// println!("uh oh");
619 /// println!("phew, nothing's broken");
623 /// The `if` keyword is used in one other place in Rust, namely as a part of pattern matching
624 /// itself, allowing patterns such as `Some(x) if x > 200` to be used.
626 /// For more information on `if` expressions, see the [Rust book] or the [Reference].
628 /// [Rust book]: ../book/ch03-05-control-flow.html#if-expressions
629 /// [Reference]: ../reference/expressions/if-expr.html
632 #[doc(keyword = "impl")]
634 /// Implement some functionality for a type.
636 /// The `impl` keyword is primarily used to define implementations on types. Inherent
637 /// implementations are standalone, while trait implementations are used to implement traits for
638 /// types, or other traits.
640 /// Functions and consts can both be defined in an implementation. A function defined in an
641 /// `impl` block can be standalone, meaning it would be called like `Foo::bar()`. If the function
642 /// takes `self`, `&self`, or `&mut self` as its first argument, it can also be called using
643 /// method-call syntax, a familiar feature to any object oriented programmer, like `foo.bar()`.
652 /// println!("boo! Example::boo() was called!");
655 /// fn answer(&mut self) {
656 /// self.number += 42;
659 /// fn get_number(&self) -> i32 {
665 /// fn do_thingy(&self);
668 /// impl Thingy for Example {
669 /// fn do_thingy(&self) {
670 /// println!("doing a thing! also, number is {}!", self.number);
675 /// For more information on implementations, see the [Rust book][book1] or the [Reference].
677 /// The other use of the `impl` keyword is in `impl Trait` syntax, which can be seen as a shorthand
678 /// for "a concrete type that implements this trait". Its primary use is working with closures,
679 /// which have type definitions generated at compile time that can't be simply typed out.
682 /// fn thing_returning_closure() -> impl Fn(i32) -> bool {
683 /// println!("here's a closure for you!");
684 /// |x: i32| x % 3 == 0
688 /// For more information on `impl Trait` syntax, see the [Rust book][book2].
690 /// [book1]: ../book/ch05-03-method-syntax.html
691 /// [Reference]: ../reference/items/implementations.html
692 /// [book2]: ../book/ch10-02-traits.html#returning-types-that-implement-traits
695 #[doc(keyword = "in")]
697 /// Iterate over a series of values with [`for`].
699 /// The expression immediately following `in` must implement the [`IntoIterator`] trait.
701 /// ## Literal Examples:
703 /// * `for _ **in** 1..3 {}` - Iterate over an exclusive range up to but excluding 3.
704 /// * `for _ **in** 1..=3 {}` - Iterate over an inclusive range up to and including 3.
706 /// (Read more about [range patterns])
708 /// [`IntoIterator`]: ../book/ch13-04-performance.html
709 /// [range patterns]: ../reference/patterns.html?highlight=range#range-patterns
710 /// [`for`]: keyword.for.html
713 #[doc(keyword = "let")]
715 /// Bind a value to a variable.
717 /// The primary use for the `let` keyword is in `let` statements, which are used to introduce a new
718 /// set of variables into the current scope, as given by a pattern.
721 /// # #![allow(unused_assignments)]
722 /// let thing1: i32 = 100;
723 /// let thing2 = 200 + thing1;
725 /// let mut changing_thing = true;
726 /// changing_thing = false;
728 /// let (part1, part2) = ("first", "second");
735 /// let Example { a, b: _ } = Example {
742 /// The pattern is most commonly a single variable, which means no pattern matching is done and
743 /// the expression given is bound to the variable. Apart from that, patterns used in `let` bindings
744 /// can be as complicated as needed, given that the pattern is exhaustive. See the [Rust
745 /// book][book1] for more information on pattern matching. The type of the pattern is optionally
746 /// given afterwards, but if left blank is automatically inferred by the compiler if possible.
748 /// Variables in Rust are immutable by default, and require the `mut` keyword to be made mutable.
750 /// Multiple variables can be defined with the same name, known as shadowing. This doesn't affect
751 /// the original variable in any way beyond being unable to directly access it beyond the point of
752 /// shadowing. It continues to remain in scope, getting dropped only when it falls out of scope.
753 /// Shadowed variables don't need to have the same type as the variables shadowing them.
756 /// let shadowing_example = true;
757 /// let shadowing_example = 123.4;
758 /// let shadowing_example = shadowing_example as u32;
759 /// let mut shadowing_example = format!("cool! {}", shadowing_example);
760 /// shadowing_example += " something else!"; // not shadowing
763 /// Other places the `let` keyword is used include along with [`if`], in the form of `if let`
764 /// expressions. They're useful if the pattern being matched isn't exhaustive, such as with
765 /// enumerations. `while let` also exists, which runs a loop with a pattern matched value until
766 /// that pattern can't be matched.
768 /// For more information on the `let` keyword, see the [Rust book][book2] or the [Reference]
770 /// [book1]: ../book/ch06-02-match.html
771 /// [`if`]: keyword.if.html
772 /// [book2]: ../book/ch18-01-all-the-places-for-patterns.html#let-statements
773 /// [Reference]: ../reference/statements.html#let-statements
776 #[doc(keyword = "while")]
778 /// Loop while a condition is upheld.
780 /// A `while` expression is used for predicate loops. The `while` expression runs the conditional
781 /// expression before running the loop body, then runs the loop body if the conditional
782 /// expression evaluates to `true`, or exits the loop otherwise.
785 /// let mut counter = 0;
787 /// while counter < 10 {
788 /// println!("{}", counter);
793 /// Like the [`for`] expression, we can use `break` and `continue`. A `while` expression
794 /// cannot break with a value and always evaluates to `()` unlike [`loop`].
802 /// break; // Exit when `i` is 64.
807 /// As `if` expressions have their pattern matching variant in `if let`, so too do `while`
808 /// expressions with `while let`. The `while let` expression matches the pattern against the
809 /// expression, then runs the loop body if pattern matching succeeds, or exits the loop otherwise.
810 /// We can use `break` and `continue` in `while let` expressions just like in `while`.
813 /// let mut counter = Some(0);
815 /// while let Some(i) = counter {
819 /// println!("{}", i);
820 /// counter = Some (i + 1);
825 /// For more information on `while` and loops in general, see the [reference].
827 /// [`for`]: keyword.for.html
828 /// [`loop`]: keyword.loop.html
829 /// [reference]: ../reference/expressions/loop-expr.html#predicate-loops
832 #[doc(keyword = "loop")]
834 /// Loop indefinitely.
836 /// `loop` is used to define the simplest kind of loop supported in Rust. It runs the code inside
837 /// it until the code uses `break` or the program exits.
841 /// println!("hello world forever!");
847 /// println!("i is {}", i);
853 /// assert_eq!(i, 128);
856 /// Unlike the other kinds of loops in Rust (`while`, `while let`, and `for`), loops can be used as
857 /// expressions that return values via `break`.
861 /// let something = loop {
867 /// assert_eq!(something, 128);
870 /// Every `break` in a loop has to have the same type. When it's not explicitly giving something,
871 /// `break;` returns `()`.
873 /// For more information on `loop` and loops in general, see the [Reference].
875 /// [Reference]: ../reference/expressions/loop-expr.html
878 #[doc(keyword = "match")]
880 /// Control flow based on pattern matching.
882 /// `match` can be used to run code conditionally. Every pattern must
883 /// be handled exhaustively either explicitly or by using wildcards like
884 /// `_` in the `match`. Since `match` is an expression, values can also be
888 /// let opt = Option::None::<usize>;
889 /// let x = match opt {
890 /// Some(int) => int,
893 /// assert_eq!(x, 10);
895 /// let a_number = Option::Some(10);
897 /// Some(x) if x <= 5 => println!("0 to 5 num = {}", x),
898 /// Some(x @ 6..=10) => println!("6 to 10 num = {}", x),
899 /// None => panic!(),
900 /// // all other numbers
905 /// `match` can be used to gain access to the inner members of an enum
906 /// and use them directly.
910 /// Double(Option<u8>, Option<String>),
911 /// Single(Option<u8>),
915 /// let get_inner = Outer::Double(None, Some(String::new()));
916 /// match get_inner {
917 /// Outer::Double(None, Some(st)) => println!("{}", st),
918 /// Outer::Single(opt) => println!("{:?}", opt),
923 /// For more information on `match` and matching in general, see the [Reference].
925 /// [Reference]: ../reference/expressions/match-expr.html
928 #[doc(keyword = "mod")]
930 /// Organize code into [modules].
932 /// Use `mod` to create new [modules] to encapsulate code, including other
938 /// type MyType = (u8, u8);
944 /// Like [`struct`]s and [`enum`]s, a module and its content are private by
945 /// default, unaccessible to code outside of the module.
947 /// To learn more about allowing access, see the documentation for the [`pub`]
950 /// [`enum`]: keyword.enum.html
951 /// [`pub`]: keyword.pub.html
952 /// [`struct`]: keyword.struct.html
953 /// [modules]: ../reference/items/modules.html
956 #[doc(keyword = "move")]
958 /// Capture a [closure]'s environment by value.
960 /// `move` converts any variables captured by reference or mutable reference
961 /// to owned by value variables.
964 /// let capture = "hello";
965 /// let closure = move || {
966 /// println!("rust says {}", capture);
970 /// Note: `move` closures may still implement [`Fn`] or [`FnMut`], even though
971 /// they capture variables by `move`. This is because the traits implemented by
972 /// a closure type are determined by *what* the closure does with captured
973 /// values, not *how* it captures them:
976 /// fn create_fn() -> impl Fn() {
977 /// let text = "Fn".to_owned();
979 /// move || println!("This is a: {}", text)
982 /// let fn_plain = create_fn();
987 /// `move` is often used when [threads] are involved.
992 /// std::thread::spawn(move || {
993 /// println!("captured {} by value", x)
994 /// }).join().unwrap();
996 /// // x is no longer available
999 /// `move` is also valid before an async block.
1002 /// let capture = "hello";
1003 /// let block = async move {
1004 /// println!("rust says {} from async block", capture);
1008 /// For more information on the `move` keyword, see the [closure]'s section
1009 /// of the Rust book or the [threads] section
1011 /// [closure]: ../book/ch13-01-closures.html
1012 /// [threads]: ../book/ch16-01-threads.html#using-move-closures-with-threads
1015 #[doc(keyword = "mut")]
1017 /// A mutable variable, reference, or pointer.
1019 /// `mut` can be used in several situations. The first is mutable variables,
1020 /// which can be used anywhere you can bind a value to a variable name. Some
1024 /// // A mutable variable in the parameter list of a function.
1025 /// fn foo(mut x: u8, y: u8) -> u8 {
1030 /// // Modifying a mutable variable.
1031 /// # #[allow(unused_assignments)]
1035 /// assert_eq!(foo(3, 4), 7);
1036 /// assert_eq!(a, 6);
1039 /// The second is mutable references. They can be created from `mut` variables
1040 /// and must be unique: no other variables can have a mutable reference, nor a
1041 /// shared reference.
1044 /// // Taking a mutable reference.
1045 /// fn push_two(v: &mut Vec<u8>) {
1049 /// // A mutable reference cannot be taken to a non-mutable variable.
1050 /// let mut v = vec![0, 1];
1051 /// // Passing a mutable reference.
1052 /// push_two(&mut v);
1054 /// assert_eq!(v, vec![0, 1, 2]);
1057 /// ```rust,compile_fail,E0502
1058 /// let mut v = vec![0, 1];
1059 /// let mut_ref_v = &mut v;
1060 /// ##[allow(unused)]
1062 /// mut_ref_v.push(2);
1065 /// Mutable raw pointers work much like mutable references, with the added
1066 /// possibility of not pointing to a valid object. The syntax is `*mut Type`.
1068 /// More information on mutable references and pointers can be found in```
1071 /// [Reference]: ../reference/types/pointer.html#mutable-references-mut
1074 #[doc(keyword = "pub")]
1076 /// Make an item visible to others.
1078 /// The keyword `pub` makes any module, function, or data structure accessible from inside
1079 /// of external modules. The `pub` keyword may also be used in a `use` declaration to re-export
1080 /// an identifier from a namespace.
1082 /// For more information on the `pub` keyword, please see the visibility section
1083 /// of the [reference] and for some examples, see [Rust by Example].
1085 /// [reference]:../reference/visibility-and-privacy.html?highlight=pub#visibility-and-privacy
1086 /// [Rust by Example]:../rust-by-example/mod/visibility.html
1089 #[doc(keyword = "ref")]
1091 /// Bind by reference during pattern matching.
1093 /// `ref` annotates pattern bindings to make them borrow rather than move.
1094 /// It is **not** a part of the pattern as far as matching is concerned: it does
1095 /// not affect *whether* a value is matched, only *how* it is matched.
1097 /// By default, [`match`] statements consume all they can, which can sometimes
1098 /// be a problem, when you don't really need the value to be moved and owned:
1100 /// ```compile_fail,E0382
1101 /// let maybe_name = Some(String::from("Alice"));
1102 /// // The variable 'maybe_name' is consumed here ...
1103 /// match maybe_name {
1104 /// Some(n) => println!("Hello, {}", n),
1105 /// _ => println!("Hello, world"),
1107 /// // ... and is now unavailable.
1108 /// println!("Hello again, {}", maybe_name.unwrap_or("world".into()));
1111 /// Using the `ref` keyword, the value is only borrowed, not moved, making it
1112 /// available for use after the [`match`] statement:
1115 /// let maybe_name = Some(String::from("Alice"));
1116 /// // Using `ref`, the value is borrowed, not moved ...
1117 /// match maybe_name {
1118 /// Some(ref n) => println!("Hello, {}", n),
1119 /// _ => println!("Hello, world"),
1121 /// // ... so it's available here!
1122 /// println!("Hello again, {}", maybe_name.unwrap_or("world".into()));
1127 /// - `&` denotes that your pattern expects a reference to an object. Hence `&`
1128 /// is a part of said pattern: `&Foo` matches different objects than `Foo` does.
1130 /// - `ref` indicates that you want a reference to an unpacked value. It is not
1131 /// matched against: `Foo(ref foo)` matches the same objects as `Foo(foo)`.
1133 /// See also the [Reference] for more information.
1135 /// [`match`]: keyword.match.html
1136 /// [Reference]: ../reference/patterns.html#identifier-patterns
1139 #[doc(keyword = "return")]
1141 /// Return a value from a function.
1143 /// A `return` marks the end of an execution path in a function:
1146 /// fn foo() -> i32 {
1149 /// assert_eq!(foo(), 3);
1152 /// `return` is not needed when the returned value is the last expression in the
1153 /// function. In this case the `;` is omitted:
1156 /// fn foo() -> i32 {
1159 /// assert_eq!(foo(), 3);
1162 /// `return` returns from the function immediately (an "early return"):
1165 /// use std::fs::File;
1166 /// use std::io::{Error, ErrorKind, Read, Result};
1168 /// fn main() -> Result<()> {
1169 /// let mut file = match File::open("foo.txt") {
1171 /// Err(e) => return Err(e),
1174 /// let mut contents = String::new();
1175 /// let size = match file.read_to_string(&mut contents) {
1177 /// Err(e) => return Err(e),
1180 /// if contents.contains("impossible!") {
1181 /// return Err(Error::new(ErrorKind::Other, "oh no!"));
1184 /// if size > 9000 {
1185 /// return Err(Error::new(ErrorKind::Other, "over 9000!"));
1188 /// assert_eq!(contents, "Hello, world!");
1192 mod return_keyword {}
1194 #[doc(keyword = "self")]
1196 /// The receiver of a method, or the current module.
1198 /// `self` is used in two situations: referencing the current module and marking
1199 /// the receiver of a method.
1201 /// In paths, `self` can be used to refer to the current module, either in a
1202 /// [`use`] statement or in a path to access an element:
1205 /// # #![allow(unused_imports)]
1206 /// use std::io::{self, Read};
1209 /// Is functionally the same as:
1212 /// # #![allow(unused_imports)]
1214 /// use std::io::Read;
1217 /// Using `self` to access an element in the current module:
1220 /// # #![allow(dead_code)]
1228 /// `self` as the current receiver for a method allows to omit the parameter
1229 /// type most of the time. With the exception of this particularity, `self` is
1230 /// used much like any other parameter:
1233 /// struct Foo(i32);
1237 /// fn new() -> Self {
1241 /// // Consuming `self`.
1242 /// fn consume(self) -> Self {
1243 /// Self(self.0 + 1)
1246 /// // Borrowing `self`.
1247 /// fn borrow(&self) -> &i32 {
1251 /// // Borrowing `self` mutably.
1252 /// fn borrow_mut(&mut self) -> &mut i32 {
1257 /// // This method must be called with a `Type::` prefix.
1258 /// let foo = Foo::new();
1259 /// assert_eq!(foo.0, 0);
1261 /// // Those two calls produces the same result.
1262 /// let foo = Foo::consume(foo);
1263 /// assert_eq!(foo.0, 1);
1264 /// let foo = foo.consume();
1265 /// assert_eq!(foo.0, 2);
1267 /// // Borrowing is handled automatically with the second syntax.
1268 /// let borrow_1 = Foo::borrow(&foo);
1269 /// let borrow_2 = foo.borrow();
1270 /// assert_eq!(borrow_1, borrow_2);
1272 /// // Borrowing mutably is handled automatically too with the second syntax.
1273 /// let mut foo = Foo::new();
1274 /// *Foo::borrow_mut(&mut foo) += 1;
1275 /// assert_eq!(foo.0, 1);
1276 /// *foo.borrow_mut() += 1;
1277 /// assert_eq!(foo.0, 2);
1280 /// Note that this automatic conversion when calling `foo.method()` is not
1281 /// limited to the examples above. See the [Reference] for more information.
1283 /// [`use`]: keyword.use.html
1284 /// [Reference]: ../reference/items/associated-items.html#methods
1287 #[doc(keyword = "Self")]
1289 /// The implementing type within a [`trait`] or [`impl`] block, or the current type within a type
1292 /// Within a type definition:
1295 /// # #![allow(dead_code)]
1298 /// // `Self` is a `Node` here.
1299 /// next: Option<Box<Self>>,
1303 /// In an [`impl`] block:
1306 /// struct Foo(i32);
1309 /// fn new() -> Self {
1314 /// assert_eq!(Foo::new().0, Foo(0).0);
1317 /// Generic parameters are implicit with `Self`:
1320 /// # #![allow(dead_code)]
1321 /// struct Wrap<T> {
1325 /// impl<T> Wrap<T> {
1326 /// fn new(elem: T) -> Self {
1332 /// In a [`trait`] definition and related [`impl`] block:
1336 /// fn example() -> Self;
1339 /// struct Foo(i32);
1341 /// impl Example for Foo {
1342 /// fn example() -> Self {
1347 /// assert_eq!(Foo::example().0, Foo(42).0);
1350 /// [`impl`]: keyword.impl.html
1351 /// [`trait`]: keyword.trait.html
1352 mod self_upper_keyword {}
1354 #[doc(keyword = "static")]
1356 /// A static item is a value which is valid for the entire duration of your
1357 /// program (a `'static` lifetime).
1359 /// On the surface, `static` items seem very similar to [`const`]s: both contain
1360 /// a value, both require type annotations and both can only be initialized with
1361 /// constant functions and values. However, `static`s are notably different in
1362 /// that they represent a location in memory. That means that you can have
1363 /// references to `static` items and potentially even modify them, making them
1364 /// essentially global variables.
1366 /// Static items do not call [`drop`] at the end of the program.
1368 /// There are two types of `static` items: those declared in association with
1369 /// the [`mut`] keyword and those without.
1371 /// Static items cannot be moved:
1373 /// ```rust,compile_fail,E0507
1374 /// static VEC: Vec<u32> = vec![];
1376 /// fn move_vec(v: Vec<u32>) -> Vec<u32> {
1380 /// // This line causes an error
1384 /// # Simple `static`s
1386 /// Accessing non-[`mut`] `static` items is considered safe, but some
1387 /// restrictions apply. Most notably, the type of a `static` value needs to
1388 /// implement the [`Sync`] trait, ruling out interior mutability containers
1389 /// like [`RefCell`]. See the [Reference] for more information.
1392 /// static FOO: [i32; 5] = [1, 2, 3, 4, 5];
1394 /// let r1 = &FOO as *const _;
1395 /// let r2 = &FOO as *const _;
1396 /// // With a strictly read-only static, references will have the same address
1397 /// assert_eq!(r1, r2);
1398 /// // A static item can be used just like a variable in many cases
1399 /// println!("{:?}", FOO);
1402 /// # Mutable `static`s
1404 /// If a `static` item is declared with the [`mut`] keyword, then it is allowed
1405 /// to be modified by the program. However, accessing mutable `static`s can
1406 /// cause undefined behavior in a number of ways, for example due to data races
1407 /// in a multithreaded context. As such, all accesses to mutable `static`s
1408 /// require an [`unsafe`] block.
1410 /// Despite their unsafety, mutable `static`s are necessary in many contexts:
1411 /// they can be used to represent global state shared by the whole program or in
1412 /// [`extern`] blocks to bind to variables from C libraries.
1414 /// In an [`extern`] block:
1417 /// # #![allow(dead_code)]
1419 /// static mut ERROR_MESSAGE: *mut std::os::raw::c_char;
1423 /// Mutable `static`s, just like simple `static`s, have some restrictions that
1424 /// apply to them. See the [Reference] for more information.
1426 /// [`const`]: keyword.const.html
1427 /// [`extern`]: keyword.extern.html
1428 /// [`mut`]: keyword.mut.html
1429 /// [`unsafe`]: keyword.unsafe.html
1430 /// [`RefCell`]: cell::RefCell
1431 /// [Reference]: ../reference/items/static-items.html
1432 mod static_keyword {}
1434 #[doc(keyword = "struct")]
1436 /// A type that is composed of other types.
1438 /// Structs in Rust come in three flavors: Structs with named fields, tuple structs, and unit
1442 /// struct Regular {
1445 /// pub field3: bool
1448 /// struct Tuple(u32, String);
1453 /// Regular structs are the most commonly used. Each field defined within them has a name and a
1454 /// type, and once defined can be accessed using `example_struct.field` syntax. The fields of a
1455 /// struct share its mutability, so `foo.bar = 2;` would only be valid if `foo` was mutable. Adding
1456 /// `pub` to a field makes it visible to code in other modules, as well as allowing it to be
1457 /// directly accessed and modified.
1459 /// Tuple structs are similar to regular structs, but its fields have no names. They are used like
1460 /// tuples, with deconstruction possible via `let TupleStruct(x, y) = foo;` syntax. For accessing
1461 /// individual variables, the same syntax is used as with regular tuples, namely `foo.0`, `foo.1`,
1462 /// etc, starting at zero.
1464 /// Unit structs are most commonly used as marker. They have a size of zero bytes, but unlike empty
1465 /// enums they can be instantiated, making them isomorphic to the unit type `()`. Unit structs are
1466 /// useful when you need to implement a trait on something, but don't need to store any data inside
1471 /// Structs can be instantiated in different ways, all of which can be mixed and
1472 /// matched as needed. The most common way to make a new struct is via a constructor method such as
1473 /// `new()`, but when that isn't available (or you're writing the constructor itself), struct
1474 /// literal syntax is used:
1477 /// # struct Foo { field1: f32, field2: String, etc: bool }
1478 /// let example = Foo {
1480 /// field2: "blah".to_string(),
1485 /// It's only possible to directly instantiate a struct using struct literal syntax when all of its
1486 /// fields are visible to you.
1488 /// There are a handful of shortcuts provided to make writing constructors more convenient, most
1489 /// common of which is the Field Init shorthand. When there is a variable and a field of the same
1490 /// name, the assignment can be simplified from `field: field` into simply `field`. The following
1491 /// example of a hypothetical constructor demonstrates this:
1500 /// pub fn new(name: String) -> Self {
1509 /// Another shortcut for struct instantiation is available, used when you need to make a new
1510 /// struct that has the same values as most of a previous struct of the same type, called struct
1514 /// # struct Foo { field1: String, field2: () }
1515 /// # let thing = Foo { field1: "".to_string(), field2: () };
1516 /// let updated_thing = Foo {
1517 /// field1: "a new value".to_string(),
1522 /// Tuple structs are instantiated in the same way as tuples themselves, except with the struct's
1523 /// name as a prefix: `Foo(123, false, 0.1)`.
1525 /// Empty structs are instantiated with just their name, and don't need anything else. `let thing =
1528 /// # Style conventions
1530 /// Structs are always written in CamelCase, with few exceptions. While the trailing comma on a
1531 /// struct's list of fields can be omitted, it's usually kept for convenience in adding and
1532 /// removing fields down the line.
1534 /// For more information on structs, take a look at the [Rust Book][book] or the
1535 /// [Reference][reference].
1537 /// [`PhantomData`]: marker::PhantomData
1538 /// [book]: ../book/ch05-01-defining-structs.html
1539 /// [reference]: ../reference/items/structs.html
1540 mod struct_keyword {}
1542 #[doc(keyword = "super")]
1544 /// The parent of the current [module].
1547 /// # #![allow(dead_code)]
1554 /// super::a::foo(); // call a's foo function
1559 /// It is also possible to use `super` multiple times: `super::super::foo`,
1560 /// going up the ancestor chain.
1562 /// See the [Reference] for more information.
1564 /// [module]: ../reference/items/modules.html
1565 /// [Reference]: ../reference/paths.html#super
1566 mod super_keyword {}
1568 #[doc(keyword = "trait")]
1570 /// A common interface for a group of types.
1572 /// A `trait` is like an interface that data types can implement. When a type
1573 /// implements a trait it can be treated abstractly as that trait using generics
1574 /// or trait objects.
1576 /// Traits can be made up of three varieties of associated items:
1578 /// - functions and methods
1582 /// Traits may also contain additional type parameters. Those type parameters
1583 /// or the trait itself can be constrained by other traits.
1585 /// Traits can serve as markers or carry other logical semantics that
1586 /// aren't expressed through their items. When a type implements that
1587 /// trait it is promising to uphold its contract. [`Send`] and [`Sync`] are two
1588 /// such marker traits present in the standard library.
1590 /// See the [Reference][Ref-Traits] for a lot more information on traits.
1594 /// Traits are declared using the `trait` keyword. Types can implement them
1595 /// using [`impl`] `Trait` [`for`] `Type`:
1599 /// const ZERO: Self;
1600 /// fn is_zero(&self) -> bool;
1603 /// impl Zero for i32 {
1604 /// const ZERO: Self = 0;
1606 /// fn is_zero(&self) -> bool {
1607 /// *self == Self::ZERO
1611 /// assert_eq!(i32::ZERO, 0);
1612 /// assert!(i32::ZERO.is_zero());
1613 /// assert!(!4.is_zero());
1616 /// With an associated type:
1622 /// fn build(&self) -> Self::Built;
1626 /// Traits can be generic, with constraints or without:
1629 /// trait MaybeFrom<T> {
1630 /// fn maybe_from(value: T) -> Option<Self>
1636 /// Traits can build upon the requirements of other traits. In the example
1637 /// below `Iterator` is a **supertrait** and `ThreeIterator` is a **subtrait**:
1640 /// trait ThreeIterator: std::iter::Iterator {
1641 /// fn next_three(&mut self) -> Option<[Self::Item; 3]>;
1645 /// Traits can be used in functions, as parameters:
1648 /// # #![allow(dead_code)]
1649 /// fn debug_iter<I: Iterator>(it: I) where I::Item: std::fmt::Debug {
1650 /// for elem in it {
1651 /// println!("{:#?}", elem);
1655 /// // u8_len_1, u8_len_2 and u8_len_3 are equivalent
1657 /// fn u8_len_1(val: impl Into<Vec<u8>>) -> usize {
1658 /// val.into().len()
1661 /// fn u8_len_2<T: Into<Vec<u8>>>(val: T) -> usize {
1662 /// val.into().len()
1665 /// fn u8_len_3<T>(val: T) -> usize
1667 /// T: Into<Vec<u8>>,
1669 /// val.into().len()
1673 /// Or as return types:
1676 /// # #![allow(dead_code)]
1677 /// fn from_zero_to(v: u8) -> impl Iterator<Item = u8> {
1678 /// (0..v).into_iter()
1682 /// The use of the [`impl`] keyword in this position allows the function writer
1683 /// to hide the concrete type as an implementation detail which can change
1684 /// without breaking user's code.
1688 /// A *trait object* is an opaque value of another type that implements a set of
1689 /// traits. A trait object implements all specified traits as well as their
1690 /// supertraits (if any).
1692 /// The syntax is the following: `dyn BaseTrait + AutoTrait1 + ... AutoTraitN`.
1693 /// Only one `BaseTrait` can be used so this will not compile:
1695 /// ```rust,compile_fail,E0225
1699 /// let _: Box<dyn A + B>;
1702 /// Neither will this, which is a syntax error:
1704 /// ```rust,compile_fail
1708 /// let _: Box<dyn A + dyn B>;
1711 /// On the other hand, this is correct:
1716 /// let _: Box<dyn A + Send + Sync>;
1719 /// The [Reference][Ref-Trait-Objects] has more information about trait objects,
1720 /// their limitations and the differences between editions.
1724 /// Some traits may be unsafe to implement. Using the [`unsafe`] keyword in
1725 /// front of the trait's declaration is used to mark this:
1728 /// unsafe trait UnsafeTrait {}
1730 /// unsafe impl UnsafeTrait for i32 {}
1733 /// # Differences between the 2015 and 2018 editions
1735 /// In the 2015 edition parameters pattern where not needed for traits:
1737 /// ```rust,edition2015
1743 /// This behavior is no longer valid in edition 2018.
1745 /// [`for`]: keyword.for.html
1746 /// [`impl`]: keyword.impl.html
1747 /// [`unsafe`]: keyword.unsafe.html
1748 /// [Ref-Traits]: ../reference/items/traits.html
1749 /// [Ref-Trait-Objects]: ../reference/types/trait-object.html
1750 mod trait_keyword {}
1752 #[doc(keyword = "true")]
1754 /// A value of type [`bool`] representing logical **true**.
1756 /// Logically `true` is not equal to [`false`].
1758 /// ## Control structures that check for **true**
1760 /// Several of Rust's control structures will check for a `bool` condition evaluating to **true**.
1762 /// * The condition in an [`if`] expression must be of type `bool`.
1763 /// Whenever that condition evaluates to **true**, the `if` expression takes
1764 /// on the value of the first block. If however, the condition evaluates
1765 /// to `false`, the expression takes on value of the `else` block if there is one.
1767 /// * [`while`] is another control flow construct expecting a `bool`-typed condition.
1768 /// As long as the condition evaluates to **true**, the `while` loop will continually
1769 /// evaluate its associated block.
1771 /// * [`match`] arms can have guard clauses on them.
1773 /// [`if`]: keyword.if.html
1774 /// [`while`]: keyword.while.html
1775 /// [`match`]: ../reference/expressions/match-expr.html#match-guards
1776 /// [`false`]: keyword.false.html
1779 #[doc(keyword = "type")]
1781 /// Define an alias for an existing type.
1783 /// The syntax is `type Name = ExistingType;`.
1787 /// `type` does **not** create a new type:
1790 /// type Meters = u32;
1791 /// type Kilograms = u32;
1793 /// let m: Meters = 3;
1794 /// let k: Kilograms = 3;
1796 /// assert_eq!(m, k);
1799 /// In traits, `type` is used to declare an [associated type]:
1802 /// trait Iterator {
1803 /// // associated type declaration
1805 /// fn next(&mut self) -> Option<Self::Item>;
1808 /// struct Once<T>(Option<T>);
1810 /// impl<T> Iterator for Once<T> {
1811 /// // associated type definition
1813 /// fn next(&mut self) -> Option<Self::Item> {
1819 /// [`trait`]: keyword.trait.html
1820 /// [associated type]: ../reference/items/associated-items.html#associated-types
1823 #[doc(keyword = "unsafe")]
1825 /// Code or interfaces whose [memory safety] cannot be verified by the type
1828 /// The `unsafe` keyword has two uses: to declare the existence of contracts the
1829 /// compiler can't check (`unsafe fn` and `unsafe trait`), and to declare that a
1830 /// programmer has checked that these contracts have been upheld (`unsafe {}`
1831 /// and `unsafe impl`, but also `unsafe fn` -- see below). They are not mutually
1832 /// exclusive, as can be seen in `unsafe fn`.
1834 /// # Unsafe abilities
1836 /// **No matter what, Safe Rust can't cause Undefined Behavior**. This is
1837 /// referred to as [soundness]: a well-typed program actually has the desired
1838 /// properties. The [Nomicon][nomicon-soundness] has a more detailed explanation
1841 /// To ensure soundness, Safe Rust is restricted enough that it can be
1842 /// automatically checked. Sometimes, however, it is necessary to write code
1843 /// that is correct for reasons which are too clever for the compiler to
1844 /// understand. In those cases, you need to use Unsafe Rust.
1846 /// Here are the abilities Unsafe Rust has in addition to Safe Rust:
1848 /// - Dereference [raw pointers]
1849 /// - Implement `unsafe` [`trait`]s
1850 /// - Call `unsafe` functions
1851 /// - Mutate [`static`]s (including [`extern`]al ones)
1852 /// - Access fields of [`union`]s
1854 /// However, this extra power comes with extra responsibilities: it is now up to
1855 /// you to ensure soundness. The `unsafe` keyword helps by clearly marking the
1856 /// pieces of code that need to worry about this.
1858 /// ## The different meanings of `unsafe`
1860 /// Not all uses of `unsafe` are equivalent: some are here to mark the existence
1861 /// of a contract the programmer must check, others are to say "I have checked
1862 /// the contract, go ahead and do this". The following
1863 /// [discussion on Rust Internals] has more in-depth explanations about this but
1864 /// here is a summary of the main points:
1866 /// - `unsafe fn`: calling this function means abiding by a contract the
1867 /// compiler cannot enforce.
1868 /// - `unsafe trait`: implementing the [`trait`] means abiding by a
1869 /// contract the compiler cannot enforce.
1870 /// - `unsafe {}`: the contract necessary to call the operations inside the
1871 /// block has been checked by the programmer and is guaranteed to be respected.
1872 /// - `unsafe impl`: the contract necessary to implement the trait has been
1873 /// checked by the programmer and is guaranteed to be respected.
1875 /// `unsafe fn` also acts like an `unsafe {}` block
1876 /// around the code inside the function. This means it is not just a signal to
1877 /// the caller, but also promises that the preconditions for the operations
1878 /// inside the function are upheld. Mixing these two meanings can be confusing
1879 /// and [proposal]s exist to use `unsafe {}` blocks inside such functions when
1880 /// making `unsafe` operations.
1882 /// See the [Rustnomicon] and the [Reference] for more informations.
1886 /// ## Marking elements as `unsafe`
1888 /// `unsafe` can be used on functions. Note that functions and statics declared
1889 /// in [`extern`] blocks are implicitly marked as `unsafe` (but not functions
1890 /// declared as `extern "something" fn ...`). Mutable statics are always unsafe,
1891 /// wherever they are declared. Methods can also be declared as `unsafe`:
1894 /// # #![allow(dead_code)]
1895 /// static mut FOO: &str = "hello";
1897 /// unsafe fn unsafe_fn() {}
1900 /// fn unsafe_extern_fn();
1901 /// static BAR: *mut u32;
1904 /// trait SafeTraitWithUnsafeMethod {
1905 /// unsafe fn unsafe_method(&self);
1911 /// unsafe fn unsafe_method_on_struct() {}
1915 /// Traits can also be declared as `unsafe`:
1918 /// unsafe trait UnsafeTrait {}
1921 /// Since `unsafe fn` and `unsafe trait` indicate that there is a safety
1922 /// contract that the compiler cannot enforce, documenting it is important. The
1923 /// standard library has many examples of this, like the following which is an
1924 /// extract from [`Vec::set_len`]. The `# Safety` section explains the contract
1925 /// that must be fulfilled to safely call the function.
1927 /// ```rust,ignore (stub-to-show-doc-example)
1928 /// /// Forces the length of the vector to `new_len`.
1930 /// /// This is a low-level operation that maintains none of the normal
1931 /// /// invariants of the type. Normally changing the length of a vector
1932 /// /// is done using one of the safe operations instead, such as
1933 /// /// `truncate`, `resize`, `extend`, or `clear`.
1937 /// /// - `new_len` must be less than or equal to `capacity()`.
1938 /// /// - The elements at `old_len..new_len` must be initialized.
1939 /// pub unsafe fn set_len(&mut self, new_len: usize)
1942 /// ## Using `unsafe {}` blocks and `impl`s
1944 /// Performing `unsafe` operations requires an `unsafe {}` block:
1947 /// # #![allow(dead_code)]
1948 /// /// Dereference the given pointer.
1952 /// /// `ptr` must be aligned and must not be dangling.
1953 /// unsafe fn deref_unchecked(ptr: *const i32) -> i32 {
1958 /// let b = &a as *const _;
1959 /// // SAFETY: `a` has not been dropped and references are always aligned,
1960 /// // so `b` is a valid address.
1961 /// unsafe { assert_eq!(*b, deref_unchecked(b)); };
1964 /// Traits marked as `unsafe` must be [`impl`]emented using `unsafe impl`. This
1965 /// makes a guarantee to other `unsafe` code that the implementation satisfies
1966 /// the trait's safety contract. The [Send] and [Sync] traits are examples of
1967 /// this behaviour in the standard library.
1970 /// /// Implementors of this trait must guarantee an element is always
1971 /// /// accessible with index 3.
1972 /// unsafe trait ThreeIndexable<T> {
1973 /// /// Returns a reference to the element with index 3 in `&self`.
1974 /// fn three(&self) -> &T;
1977 /// // The implementation of `ThreeIndexable` for `[T; 4]` is `unsafe`
1978 /// // because the implementor must abide by a contract the compiler cannot
1979 /// // check but as a programmer we know there will always be a valid element
1980 /// // at index 3 to access.
1981 /// unsafe impl<T> ThreeIndexable<T> for [T; 4] {
1982 /// fn three(&self) -> &T {
1983 /// // SAFETY: implementing the trait means there always is an element
1984 /// // with index 3 accessible.
1985 /// unsafe { self.get_unchecked(3) }
1989 /// let a = [1, 2, 4, 8];
1990 /// assert_eq!(a.three(), &8);
1993 /// [`extern`]: keyword.extern.html
1994 /// [`trait`]: keyword.trait.html
1995 /// [`static`]: keyword.static.html
1996 /// [`union`]: keyword.union.html
1997 /// [`impl`]: keyword.impl.html
1998 /// [raw pointers]: ../reference/types/pointer.html
1999 /// [memory safety]: ../book/ch19-01-unsafe-rust.html
2000 /// [Rustnomicon]: ../nomicon/index.html
2001 /// [nomicon-soundness]: ../nomicon/safe-unsafe-meaning.html
2002 /// [soundness]: https://rust-lang.github.io/unsafe-code-guidelines/glossary.html#soundness-of-code--of-a-library
2003 /// [Reference]: ../reference/unsafety.html
2004 /// [proposal]: https://github.com/rust-lang/rfcs/pull/2585
2005 /// [discussion on Rust Internals]: https://internals.rust-lang.org/t/what-does-unsafe-mean/6696
2006 mod unsafe_keyword {}
2008 #[doc(keyword = "use")]
2010 /// Import or rename items from other crates or modules.
2012 /// Usually a `use` keyword is used to shorten the path required to refer to a module item.
2013 /// The keyword may appear in modules, blocks and even functions, usually at the top.
2015 /// The most basic usage of the keyword is `use path::to::item;`,
2016 /// though a number of convenient shortcuts are supported:
2018 /// * Simultaneously binding a list of paths with a common prefix,
2019 /// using the glob-like brace syntax `use a::b::{c, d, e::f, g::h::i};`
2020 /// * Simultaneously binding a list of paths with a common prefix and their common parent module,
2021 /// using the [`self`] keyword, such as `use a::b::{self, c, d::e};`
2022 /// * Rebinding the target name as a new local name, using the syntax `use p::q::r as x;`.
2023 /// This can also be used with the last two features: `use a::b::{self as ab, c as abc}`.
2024 /// * Binding all paths matching a given prefix,
2025 /// using the asterisk wildcard syntax `use a::b::*;`.
2026 /// * Nesting groups of the previous features multiple times,
2027 /// such as `use a::b::{self as ab, c, d::{*, e::f}};`
2028 /// * Reexporting with visibility modifiers such as `pub use a::b;`
2029 /// * Importing with `_` to only import the methods of a trait without binding it to a name
2030 /// (to avoid conflict for example): `use ::std::io::Read as _;`.
2032 /// Using path qualifiers like [`crate`], [`super`] or [`self`] is supported: `use crate::a::b;`.
2034 /// Note that when the wildcard `*` is used on a type, it does not import its methods (though
2035 /// for `enum`s it imports the variants, as shown in the example below).
2037 /// ```compile_fail,edition2018
2038 /// enum ExampleEnum {
2043 /// impl ExampleEnum {
2044 /// fn new() -> Self {
2049 /// use ExampleEnum::*;
2052 /// let _ = VariantA;
2054 /// // Does not compile !
2058 /// For more information on `use` and paths in general, see the [Reference].
2060 /// The differences about paths and the `use` keyword between the 2015 and 2018 editions
2061 /// can also be found in the [Reference].
2063 /// [`crate`]: keyword.crate.html
2064 /// [`self`]: keyword.self.html
2065 /// [`super`]: keyword.super.html
2066 /// [Reference]: ../reference/items/use-declarations.html
2069 #[doc(keyword = "where")]
2071 /// Add constraints that must be upheld to use an item.
2073 /// `where` allows specifying constraints on lifetime and generic parameters.
2074 /// The [RFC] introducing `where` contains detailed informations about the
2079 /// `where` can be used for constraints with traits:
2082 /// fn new<T: Default>() -> T {
2086 /// fn new_where<T>() -> T
2093 /// assert_eq!(0.0, new());
2094 /// assert_eq!(0.0, new_where());
2096 /// assert_eq!(0, new());
2097 /// assert_eq!(0, new_where());
2100 /// `where` can also be used for lifetimes.
2102 /// This compiles because `longer` outlives `shorter`, thus the constraint is
2106 /// fn select<'short, 'long>(s1: &'short str, s2: &'long str, second: bool) -> &'short str
2110 /// if second { s2 } else { s1 }
2113 /// let outer = String::from("Long living ref");
2114 /// let longer = &outer;
2116 /// let inner = String::from("Short living ref");
2117 /// let shorter = &inner;
2119 /// assert_eq!(select(shorter, longer, false), shorter);
2120 /// assert_eq!(select(shorter, longer, true), longer);
2124 /// On the other hand, this will not compile because the `where 'b: 'a` clause
2125 /// is missing: the `'b` lifetime is not known to live at least as long as `'a`
2126 /// which means this function cannot ensure it always returns a valid reference:
2128 /// ```rust,compile_fail,E0623
2129 /// fn select<'a, 'b>(s1: &'a str, s2: &'b str, second: bool) -> &'a str
2131 /// if second { s2 } else { s1 }
2135 /// `where` can also be used to express more complicated constraints that cannot
2136 /// be written with the `<T: Trait>` syntax:
2139 /// fn first_or_default<I>(mut i: I) -> I::Item
2142 /// I::Item: Default,
2144 /// i.next().unwrap_or_else(I::Item::default)
2147 /// assert_eq!(first_or_default(vec![1, 2, 3].into_iter()), 1);
2148 /// assert_eq!(first_or_default(Vec::<i32>::new().into_iter()), 0);
2151 /// `where` is available anywhere generic and lifetime parameters are available,
2152 /// as can be seen with the [`Cow`](crate::borrow::Cow) type from the standard
2156 /// # #![allow(dead_code)]
2157 /// pub enum Cow<'a, B>
2159 /// B: 'a + ToOwned + ?Sized,
2161 /// Borrowed(&'a B),
2162 /// Owned(<B as ToOwned>::Owned),
2166 /// [RFC]: https://github.com/rust-lang/rfcs/blob/master/text/0135-where.md
2167 mod where_keyword {}
2169 // 2018 Edition keywords
2171 #[doc(keyword = "async")]
2173 /// Return a [`Future`] instead of blocking the current thread.
2175 /// Use `async` in front of `fn`, `closure`, or a `block` to turn the marked code into a `Future`.
2176 /// As such the code will not be run immediately, but will only be evaluated when the returned
2177 /// future is `.await`ed.
2179 /// We have written an [async book] detailing async/await and trade-offs compared to using threads.
2183 /// `async` is a keyword from the 2018 edition onwards.
2185 /// It is available for use in stable rust from version 1.39 onwards.
2187 /// [`Future`]: future::Future
2188 /// [async book]: https://rust-lang.github.io/async-book/
2189 mod async_keyword {}
2191 #[doc(keyword = "await")]
2193 /// Suspend execution until the result of a [`Future`] is ready.
2195 /// `.await`ing a future will suspend the current function's execution until the `executor`
2196 /// has run the future to completion.
2198 /// Read the [async book] for details on how async/await and executors work.
2202 /// `await` is a keyword from the 2018 edition onwards.
2204 /// It is available for use in stable rust from version 1.39 onwards.
2206 /// [`Future`]: future::Future
2207 /// [async book]: https://rust-lang.github.io/async-book/
2208 mod await_keyword {}
2210 #[doc(keyword = "dyn")]
2212 /// `dyn` is a prefix of a [trait object]'s type.
2214 /// The `dyn` keyword is used to highlight that calls to methods on the associated `Trait`
2215 /// are dynamically dispatched. To use the trait this way, it must be 'object safe'.
2217 /// Unlike generic parameters or `impl Trait`, the compiler does not know the concrete type that
2218 /// is being passed. That is, the type has been [erased].
2219 /// As such, a `dyn Trait` reference contains _two_ pointers.
2220 /// One pointer goes to the data (e.g., an instance of a struct).
2221 /// Another pointer goes to a map of method call names to function pointers
2222 /// (known as a virtual method table or vtable).
2224 /// At run-time, when a method needs to be called on the `dyn Trait`, the vtable is consulted to get
2225 /// the function pointer and then that function pointer is called.
2229 /// The above indirection is the additional runtime cost of calling a function on a `dyn Trait`.
2230 /// Methods called by dynamic dispatch generally cannot be inlined by the compiler.
2232 /// However, `dyn Trait` is likely to produce smaller code than `impl Trait` / generic parameters as
2233 /// the method won't be duplicated for each concrete type.
2235 /// Read more about `object safety` and [trait object]s.
2237 /// [trait object]: ../book/ch17-02-trait-objects.html
2238 /// [erased]: https://en.wikipedia.org/wiki/Type_erasure
2241 #[doc(keyword = "union")]
2243 /// The [Rust equivalent of a C-style union][union].
2245 /// A `union` looks like a [`struct`] in terms of declaration, but all of its
2246 /// fields exist in the same memory, superimposed over one another. For instance,
2247 /// if we wanted some bits in memory that we sometimes interpret as a `u32` and
2248 /// sometimes as an `f32`, we could write:
2251 /// union IntOrFloat {
2256 /// let mut u = IntOrFloat { f: 1.0 };
2257 /// // Reading the fields of an union is always unsafe
2258 /// assert_eq!(unsafe { u.i }, 1065353216);
2259 /// // Updating through any of the field will modify all of them
2260 /// u.i = 1073741824;
2261 /// assert_eq!(unsafe { u.f }, 2.0);
2264 /// # Matching on unions
2266 /// It is possible to use pattern matching on `union`s. A single field name must
2267 /// be used and it must match the name of one of the `union`'s field.
2268 /// Like reading from a `union`, pattern matching on a `union` requires `unsafe`.
2271 /// union IntOrFloat {
2276 /// let u = IntOrFloat { f: 1.0 };
2280 /// IntOrFloat { i: 10 } => println!("Found exactly ten!"),
2281 /// // Matching the field `f` provides an `f32`.
2282 /// IntOrFloat { f } => println!("Found f = {} !", f),
2287 /// # References to union fields
2289 /// All fields in a `union` are all at the same place in memory which means
2290 /// borrowing one borrows the entire `union`, for the same lifetime:
2292 /// ```rust,compile_fail,E0502
2293 /// union IntOrFloat {
2298 /// let mut u = IntOrFloat { f: 1.0 };
2300 /// let f = unsafe { &u.f };
2301 /// // This will not compile because the field has already been borrowed, even
2302 /// // if only immutably
2303 /// let i = unsafe { &mut u.i };
2306 /// println!("f = {} and i = {}", f, i);
2309 /// See the [Reference][union] for more informations on `union`s.
2311 /// [`struct`]: keyword.struct.html
2312 /// [union]: ../reference/items/unions.html
2313 mod union_keyword {}