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