3 /// The keyword for casting a value to a type.
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]
29 /// https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions
30 /// [`crate`]: keyword.crate.html
33 #[doc(keyword = "const")]
35 /// The keyword for defining constants.
37 /// Sometimes a certain value is used many times throughout a program, and it can become
38 /// inconvenient to copy it over and over. What's more, it's not always possible or desirable to
39 /// make it a variable that gets carried around to each function that needs it. In these cases, the
40 /// `const` keyword provides a convenient alternative to code duplication.
43 /// const THING: u32 = 0xABAD1DEA;
45 /// let foo = 123 + THING;
48 /// Constants must be explicitly typed, unlike with `let` you can't ignore its type and let the
49 /// compiler figure it out. Any constant value can be defined in a const, which in practice happens
50 /// to be most things that would be reasonable to have a constant (barring `const fn`s). For
51 /// example, you can't have a File as a `const`.
53 /// The only lifetime allowed in a constant is `'static`, which is the lifetime that encompasses
54 /// all others in a Rust program. For example, if you wanted to define a constant string, it would
58 /// const WORDS: &str = "hello rust!";
61 /// Thanks to static lifetime elision, you usually don't have to explicitly use 'static:
64 /// const WORDS: &str = "hello convenience!";
67 /// `const` items looks remarkably similar to `static` items, which introduces some confusion as
68 /// to which one should be used at which times. To put it simply, constants are inlined wherever
69 /// they're used, making using them identical to simply replacing the name of the const with its
70 /// value. Static variables on the other hand point to a single location in memory, which all
71 /// accesses share. This means that, unlike with constants, they can't have destructors, and act as
72 /// a single value across the entire codebase.
74 /// Constants, as with statics, should always be in SCREAMING_SNAKE_CASE.
76 /// The `const` keyword is also used in raw pointers in combination with `mut`, as seen in `*const
77 /// T` and `*mut T`. More about that can be read at the [pointer] primitive part of the Rust docs.
79 /// For more detail on `const`, see the [Rust Book] or the [Reference]
81 /// [pointer]: primitive.pointer.html
83 /// https://doc.rust-lang.org/stable/book/2018-edition/ch03-01-variables-and-mutability.html#differences-between-variables-and-constants
84 /// [Reference]: https://doc.rust-lang.org/reference/items/constant-items.html
87 #[doc(keyword = "crate")]
89 /// The `crate` keyword.
91 /// The primary use of the `crate` keyword is as a part of `extern crate` declarations, which are
92 /// used to specify a dependency on a crate external to the one it's declared in. Crates are the
93 /// fundamental compilation unit of Rust code, and can be seen as libraries or projects. More can
94 /// be read about crates in the [Reference].
97 /// extern crate rand;
98 /// extern crate my_crate as thing;
99 /// extern crate std; // implicitly added to the root of every Rust project
102 /// The `as` keyword can be used to change what the crate is referred to as in your project. If a
103 /// crate name includes a dash, it is implicitly imported with the dashes replaced by underscores.
105 /// `crate` is also used as in conjunction with `pub` to signify that the item it's attached to
106 /// is public only to other members of the same crate it's in.
109 /// # #[allow(unused_imports)]
110 /// pub(crate) use std::io::Error as IoError;
111 /// pub(crate) enum CoolMarkerType { }
112 /// pub struct PublicThing {
113 /// pub(crate) semi_secret_thing: bool,
117 /// [Reference]: https://doc.rust-lang.org/reference/items/extern-crates.html
118 mod crate_keyword { }
120 #[doc(keyword = "enum")]
122 /// For defining enumerations.
124 /// Enums in Rust are similar to those of other compiled languages like C, but have important
125 /// differences that make them considerably more powerful. What Rust calls enums are more commonly
126 /// known as [Algebraic Data Types] if you're coming from a functional programming background. The
127 /// important detail is that each enum variant can have data to go along with it.
131 /// enum SimpleEnum {
143 /// enum ComplexEnum {
147 /// usual_struct_stuff: bool,
152 /// enum EmptyEnum { }
155 /// The first enum shown is the usual kind of enum you'd find in a C-style language. The second
156 /// shows off a hypothetical example of something storing location data, with `Coord` being any
157 /// other type that's needed, for example a struct. The third example demonstrates the kind of
158 /// data a variant can store, ranging from nothing, to a tuple, to an anonymous struct.
160 /// Instantiating enum variants involves explicitly using the enum's name as its namespace,
161 /// followed by one of its variants. `SimpleEnum::SecondVariant` would be an example from above.
162 /// When data follows along with a variant, such as with rust's built-in [`Option`] type, the data
163 /// is added as the type describes, for example `Option::Some(123)`. The same follows with
164 /// struct-like variants, with things looking like `ComplexEnum::LotsOfThings { usual_struct_stuff:
165 /// true, blah: "hello!".to_string(), }`. Empty Enums are similar to () in that they cannot be
166 /// instantiated at all, and are used mainly to mess with the type system in interesting ways.
168 /// For more information, take a look at the [Rust Book] or the [Reference]
170 /// [Algebraic Data Types]: https://en.wikipedia.org/wiki/Algebraic_data_type
171 /// [`Option`]: option/enum.Option.html
172 /// [Rust Book]: https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html
173 /// [Reference]: https://doc.rust-lang.org/reference/items/enumerations.html
176 #[doc(keyword = "extern")]
178 /// For external connections in Rust code.
180 /// The `extern` keyword is used in two places in Rust. One is in conjunction with the [`crate`]
181 /// keyword to make your Rust code aware of other Rust crates in your project, i.e., `extern crate
182 /// lazy_static;`. The other use is in foreign function interfaces (FFI).
184 /// `extern` is used in two different contexts within FFI. The first is in the form of external
185 /// blocks, for declaring function interfaces that Rust code can call foreign code by.
188 /// #[link(name = "my_c_library")]
190 /// fn my_c_function(x: i32) -> bool;
194 /// This code would attempt to link with `libmy_c_library.so` on unix-like systems and
195 /// `my_c_library.dll` on Windows at runtime, and panic if it can't find something to link to. Rust
196 /// code could then use `my_c_function` as if it were any other unsafe Rust function. Working with
197 /// non-Rust languages and FFI is inherently unsafe, so wrappers are usually built around C APIs.
199 /// The mirror use case of FFI is also done via the `extern` keyword:
203 /// pub extern fn callable_from_c(x: i32) -> bool {
208 /// If compiled as a dylib, the resulting .so could then be linked to from a C library, and the
209 /// function could be used as if it was from any other library.
211 /// For more information on FFI, check the [Rust book] or the [Reference].
214 /// https://doc.rust-lang.org/book/ch19-01-unsafe-rust.html#using-extern-functions-to-call-external-code
215 /// [Reference]: https://doc.rust-lang.org/reference/items/external-blocks.html
216 mod extern_keyword { }
218 #[doc(keyword = "fn")]
220 /// The keyword for defining functions.
222 /// Functions are the primary way code is executed within Rust. Function blocks, usually just
223 /// called functions, can be defined in a variety of different places and be assigned many
224 /// different attributes and modifiers.
226 /// Standalone functions that just sit within a module not attached to anything else are common,
227 /// but most functions will end up being inside [`impl`] blocks, either on another type itself, or
228 /// as a trait impl for that type.
231 /// fn standalone_function() {
235 /// pub fn public_thing(argument: bool) -> String {
245 /// pub fn new() -> Self {
253 /// In addition to presenting fixed types in the form of `fn name(arg: type, ..) -> return_type`,
254 /// functions can also declare a list of type parameters along with trait bounds that they fall
258 /// fn generic_function<T: Clone>(x: T) -> (T, T, T) {
259 /// (x.clone(), x.clone(), x.clone())
262 /// fn generic_where<T>(x: T) -> T
263 /// where T: std::ops::Add<Output=T> + Copy
269 /// Declaring trait bounds in the angle brackets is functionally identical to using a `where`
270 /// clause. It's up to the programmer to decide which works better in each situation, but `where`
271 /// tends to be better when things get longer than one line.
273 /// Along with being made public via `pub`, `fn` can also have an [`extern`] added for use in
276 /// For more information on the various types of functions and how they're used, consult the [Rust
277 /// book] or the [Reference].
279 /// [`impl`]: keyword.impl.html
280 /// [`extern`]: keyword.extern.html
281 /// [Rust book]: https://doc.rust-lang.org/book/ch03-03-how-functions-work.html
282 /// [Reference]: https://doc.rust-lang.org/reference/items/functions.html
285 #[doc(keyword = "for")]
287 /// The `for` keyword.
289 /// `for` is primarily used in for-in-loops, but it has a few other pieces of syntactic uses such as
290 /// `impl Trait for Type` (see [`impl`] for more info on that). for-in-loops, or to be more
291 /// precise, iterator loops, are a simple syntactic sugar over an exceedingly common practice
292 /// within Rust, which is to loop over an iterator until that iterator returns None (or `break`
297 /// println!("{}", i * 2);
300 /// for i in std::iter::repeat(5) {
301 /// println!("turns out {} never stops being 5", i);
302 /// break; // would loop forever otherwise
305 /// 'outer: for x in 5..50 {
314 /// As shown in the example above, `for` loops (along with all other loops) can be tagged, using
315 /// similar syntax to lifetimes (only visually similar, entirely distinct in practice). Giving the
316 /// same tag to `break` breaks the tagged loop, which is useful for inner loops. It is definitely
319 /// A `for` loop expands as shown:
323 /// # let iterator = 0..2;
324 /// for loop_variable in iterator {
331 /// # let iterator = 0..2;
333 /// let mut _iter = std::iter::IntoIterator::into_iter(iterator);
335 /// match _iter.next() {
336 /// Some(loop_variable) => {
345 /// More details on the functionality shown can be seen at the [`IntoIterator`] docs.
347 /// For more information on for-loops, see the [Rust book] or the [Reference].
349 /// [`impl`]: keyword.impl.html
350 /// [`IntoIterator`]: iter/trait.IntoIterator.html
352 /// https://doc.rust-lang.org/book/2018-edition/ch03-05-control-flow.html#looping-through-a-collection-with-for
353 /// [Reference]: https://doc.rust-lang.org/reference/expressions/loop-expr.html#iterator-loops
356 #[doc(keyword = "if")]
358 /// If statements and expressions.
360 /// `if` is a familiar construct to most programmers, and is the main way you'll often do logic in
361 /// your code. However, unlike in most languages, `if` blocks can also act as expressions.
364 /// # let rude = true;
366 /// println!("whoops, mathematics broke");
368 /// println!("everything's fine!");
371 /// let greeting = if rude {
377 /// if let Ok(x) = "123".parse::<i32>() {
378 /// println!("{} double that and you get {}!", greeting, x * 2);
382 /// Shown above are the three typical forms an `if` block comes in. First is the usual kind of
383 /// thing you'd see in many languages, with an optional `else` block. Second uses `if` as an
384 /// expression, which is only possible if all branches return the same type. An `if` expression can
385 /// be used everywhere you'd expect. The third kind of `if` block is an `if let` block, which
386 /// behaves similarly to using a `match` expression:
389 /// if let Some(x) = Some(123) {
393 /// // something else
396 /// match Some(123) {
402 /// // something else
407 /// Each kind of `if` expression can be mixed and matched as needed.
410 /// if true == false {
411 /// println!("oh no");
412 /// } else if "something" == "other thing" {
413 /// println!("oh dear");
414 /// } else if let Some(200) = "blarg".parse::<i32>().ok() {
415 /// println!("uh oh");
417 /// println!("phew, nothing's broken");
421 /// The `if` keyword is used in one other place in Rust, namely as a part of pattern matching
422 /// itself, allowing patterns such as `Some(x) if x > 200` to be used.
424 /// For more information on `if` expressions, see the [Rust book] or the [Reference].
427 /// https://doc.rust-lang.org/stable/book/2018-edition/ch03-05-control-flow.html#if-expressions
428 /// [Reference]: https://doc.rust-lang.org/reference/expressions/if-expr.html
431 #[doc(keyword = "impl")]
433 /// The implementation-defining keyword.
435 /// The `impl` keyword is primarily used to define implementations on types. Inherent
436 /// implementations are standalone, while trait implementations are used to implement traits for
437 /// types, or other traits.
439 /// Functions and consts can both be defined in an implementation. A function defined in an
440 /// `impl` block can be standalone, meaning it would be called like `Foo::bar()`. If the function
441 /// takes `self`, `&self`, or `&mut self` as its first argument, it can also be called using
442 /// method-call syntax, a familiar feature to any object oriented programmer, like `foo.bar()`.
451 /// println!("boo! Example::boo() was called!");
454 /// fn answer(&mut self) {
455 /// self.number += 42;
458 /// fn get_number(&self) -> i32 {
464 /// fn do_thingy(&self);
467 /// impl Thingy for Example {
468 /// fn do_thingy(&self) {
469 /// println!("doing a thing! also, number is {}!", self.number);
474 /// For more information on implementations, see the [Rust book][book1] or the [Reference].
476 /// The other use of the `impl` keyword is in `impl Trait` syntax, which can be seen as a shorthand
477 /// for "a concrete type that implements this trait". Its primary use is working with closures,
478 /// which have type definitions generated at compile time that can't be simply typed out.
481 /// fn thing_returning_closure() -> impl Fn(i32) -> bool {
482 /// println!("here's a closure for you!");
483 /// |x: i32| x % 3 == 0
487 /// For more information on `impl Trait` syntax, see the [Rust book][book2].
489 /// [book1]: https://doc.rust-lang.org/stable/book/2018-edition/ch05-03-method-syntax.html
490 /// [Reference]: https://doc.rust-lang.org/reference/items/implementations.html
492 /// https://doc.rust-lang.org/stable/book/2018-edition/ch10-02-traits.html#returning-traits
495 #[doc(keyword = "let")]
497 /// The variable binding keyword.
499 /// The primary use for the `let` keyword is in `let` statements, which are used to introduce a new
500 /// set of variables into the current scope, as given by a pattern.
503 /// # #![allow(unused_assignments)]
504 /// let thing1: i32 = 100;
505 /// let thing2 = 200 + thing1;
507 /// let mut changing_thing = true;
508 /// changing_thing = false;
510 /// let (part1, part2) = ("first", "second");
517 /// let Example { a, b: _ } = Example {
524 /// The pattern is most commonly a single variable, which means no pattern matching is done and
525 /// the expression given is bound to the variable. Apart from that, patterns used in `let` bindings
526 /// can be as complicated as needed, given that the pattern is exhaustive. See the [Rust
527 /// book][book1] for more information on pattern matching. The type of the pattern is optionally
528 /// given afterwards, but if left blank is automatically inferred by the compiler if possible.
530 /// Variables in Rust are immutable by default, and require the `mut` keyword to be made mutable.
532 /// Multiple variables can be defined with the same name, known as shadowing. This doesn't affect
533 /// the original variable in any way beyond being unable to directly access it beyond the point of
534 /// shadowing. It continues to remain in scope, getting dropped only when it falls out of scope.
535 /// Shadowed variables don't need to have the same type as the variables shadowing them.
538 /// let shadowing_example = true;
539 /// let shadowing_example = 123.4;
540 /// let shadowing_example = shadowing_example as u32;
541 /// let mut shadowing_example = format!("cool! {}", shadowing_example);
542 /// shadowing_example += " something else!"; // not shadowing
545 /// Other places the `let` keyword is used include along with [`if`], in the form of `if let`
546 /// expressions. They're useful if the pattern being matched isn't exhaustive, such as with
547 /// enumerations. `while let` also exists, which runs a loop with a pattern matched value until
548 /// that pattern can't be matched.
550 /// For more information on the `let` keyword, see the [Rust book] or the [Reference]
552 /// [book1]: https://doc.rust-lang.org/stable/book/2018-edition/ch06-02-match.html
553 /// [`if`]: keyword.if.html
555 /// https://doc.rust-lang.org/stable/book/2018-edition/ch18-01-all-the-places-for-patterns.html#let-statements
556 /// [Reference]: https://doc.rust-lang.org/reference/statements.html#let-statements
559 #[doc(keyword = "loop")]
561 /// The loop-defining keyword.
563 /// `loop` is used to define the simplest kind of loop supported in Rust. It runs the code inside
564 /// it until the code uses `break` or the program exits.
568 /// println!("hello world forever!");
574 /// println!("i is {}", i);
582 /// Unlike the other kinds of loops in Rust (`while`, `while let`, and `for`), loops can be used as
583 /// expressions that return values via `break`.
587 /// let something = loop {
593 /// assert_eq!(something, 128);
596 /// Every `break` in a loop has to have the same type. When it's not explicitly giving something,
597 /// `break;` returns `()`.
599 /// For more information on `loop` and loops in general, see the [Reference].
601 /// [Reference]: https://doc.rust-lang.org/reference/expressions/loop-expr.html
604 #[doc(keyword = "struct")]
606 /// The keyword used to define structs.
608 /// Structs in Rust come in three flavors: Structs with named fields, tuple structs, and unit
618 /// struct Tuple(u32, String);
623 /// Regular structs are the most commonly used. Each field defined within them has a name and a
624 /// type, and once defined can be accessed using `example_struct.field` syntax. The fields of a
625 /// struct share its mutability, so `foo.bar = 2;` would only be valid if `foo` was mutable. Adding
626 /// `pub` to a field makes it visible to code in other modules, as well as allowing it to be
627 /// directly accessed and modified.
629 /// Tuple structs are similar to regular structs, but its fields have no names. They are used like
630 /// tuples, with deconstruction possible via `let TupleStruct(x, y) = foo;` syntax. For accessing
631 /// individual variables, the same syntax is used as with regular tuples, namely `foo.0`, `foo.1`,
632 /// etc, starting at zero.
634 /// Unit structs are most commonly used as marker. They have a size of zero bytes, but unlike empty
635 /// enums they can be instantiated, making them isomorphic to the unit type `()`. Unit structs are
636 /// useful when you need to implement a trait on something, but don't need to store any data inside
641 /// Structs can be instantiated in different ways, all of which can be mixed and
642 /// matched as needed. The most common way to make a new struct is via a constructor method such as
643 /// `new()`, but when that isn't available (or you're writing the constructor itself), struct
644 /// literal syntax is used:
647 /// # struct Foo { field1: f32, field2: String, etc: bool }
648 /// let example = Foo {
650 /// field2: "blah".to_string(),
655 /// It's only possible to directly instantiate a struct using struct literal syntax when all of its
656 /// fields are visible to you.
658 /// There are a handful of shortcuts provided to make writing constructors more convenient, most
659 /// common of which is the Field Init shorthand. When there is a variable and a field of the same
660 /// name, the assignment can be simplified from `field: field` into simply `field`. The following
661 /// example of a hypothetical constructor demonstrates this:
670 /// pub fn new(name: String) -> Self {
679 /// Another shortcut for struct instantiation is available, used when you need to make a new
680 /// struct that has the same values as most of a previous struct of the same type, called struct
684 /// # struct Foo { field1: String, field2: () }
685 /// # let thing = Foo { field1: "".to_string(), field2: () };
686 /// let updated_thing = Foo {
687 /// field1: "a new value".to_string(),
692 /// Tuple structs are instantiated in the same way as tuples themselves, except with the struct's
693 /// name as a prefix: `Foo(123, false, 0.1)`.
695 /// Empty structs are instantiated with just their name, and don't need anything else. `let thing =
698 /// # Style conventions
700 /// Structs are always written in CamelCase, with few exceptions. While the trailing comma on a
701 /// struct's list of fields can be omitted, it's usually kept for convenience in adding and
702 /// removing fields down the line.
704 /// For more information on structs, take a look at the [Rust Book][book] or the
705 /// [Reference][reference].
707 /// [`PhantomData`]: marker/struct.PhantomData.html
708 /// [book]: https://doc.rust-lang.org/book/ch05-01-defining-structs.html
709 /// [reference]: https://doc.rust-lang.org/reference/items/structs.html
710 mod struct_keyword { }