]>
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`, | |
29967ef6 XL |
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; | |
0bf4aa26 XL |
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 | /// | |
fc512014 XL |
23 | /// `as` can be seen as the primitive for `From` and `Into`: `as` only works with primitives |
24 | /// (`u8`, `bool`, `str`, pointers, ...) whereas `From` and `Into` also works with types like | |
25 | /// `String` or `Vec`. | |
26 | /// | |
27 | /// `as` can also be used with the `_` placeholder when the destination type can be inferred. Note | |
28 | /// that this can cause inference breakage and usually such code should use an explicit type for | |
29 | /// both clarity and stability. This is most useful when converting pointers using `as *const _` or | |
30 | /// `as *mut _` though the [`cast`][const-cast] method is recommended over `as *const _` and it is | |
31 | /// [the same][mut-cast] for `as *mut _`: those methods make the intent clearer. | |
32 | /// | |
33 | /// `as` is also used to rename imports in [`use`] and [`extern crate`][`crate`] statements: | |
0bf4aa26 | 34 | /// |
29967ef6 XL |
35 | /// ``` |
36 | /// # #[allow(unused_imports)] | |
37 | /// use std::{mem as memory, net as network}; | |
38 | /// // Now you can use the names `memory` and `network` to refer to `std::mem` and `std::net`. | |
39 | /// ``` | |
29967ef6 | 40 | /// For more information on what `as` is capable of, see the [Reference]. |
0bf4aa26 | 41 | /// |
48663c56 | 42 | /// [Reference]: ../reference/expressions/operator-expr.html#type-cast-expressions |
fc512014 | 43 | /// [`crate`]: keyword.crate.html |
29967ef6 | 44 | /// [`use`]: keyword.use.html |
6a06907d | 45 | /// [const-cast]: pointer::cast |
fc512014 | 46 | /// [mut-cast]: primitive.pointer.html#method.cast-1 |
dfeec247 | 47 | mod as_keyword {} |
0bf4aa26 | 48 | |
48663c56 XL |
49 | #[doc(keyword = "break")] |
50 | // | |
51 | /// Exit early from a loop. | |
52 | /// | |
e74abb32 XL |
53 | /// When `break` is encountered, execution of the associated loop body is |
54 | /// immediately terminated. | |
55 | /// | |
56 | /// ```rust | |
57 | /// let mut last = 0; | |
58 | /// | |
59 | /// for x in 1..100 { | |
60 | /// if x > 12 { | |
61 | /// break; | |
62 | /// } | |
63 | /// last = x; | |
64 | /// } | |
65 | /// | |
66 | /// assert_eq!(last, 12); | |
5e7ed085 | 67 | /// println!("{last}"); |
e74abb32 XL |
68 | /// ``` |
69 | /// | |
70 | /// A break expression is normally associated with the innermost loop enclosing the | |
71 | /// `break` but a label can be used to specify which enclosing loop is affected. | |
72 | /// | |
923072b8 | 73 | /// ```rust |
e74abb32 | 74 | /// 'outer: for i in 1..=5 { |
5e7ed085 | 75 | /// println!("outer iteration (i): {i}"); |
e74abb32 | 76 | /// |
60c5eb7d | 77 | /// '_inner: for j in 1..=200 { |
5e7ed085 | 78 | /// println!(" inner iteration (j): {j}"); |
e74abb32 | 79 | /// if j >= 3 { |
c295e0f8 | 80 | /// // breaks from inner loop, lets outer loop continue. |
e74abb32 XL |
81 | /// break; |
82 | /// } | |
83 | /// if i >= 2 { | |
84 | /// // breaks from outer loop, and directly to "Bye". | |
85 | /// break 'outer; | |
86 | /// } | |
87 | /// } | |
88 | /// } | |
89 | /// println!("Bye."); | |
923072b8 | 90 | /// ``` |
e74abb32 XL |
91 | /// |
92 | /// When associated with `loop`, a break expression may be used to return a value from that loop. | |
93 | /// This is only valid with `loop` and not with any other type of loop. | |
94 | /// If no value is specified, `break;` returns `()`. | |
95 | /// Every `break` within a loop must return the same type. | |
96 | /// | |
97 | /// ```rust | |
98 | /// let (mut a, mut b) = (1, 1); | |
99 | /// let result = loop { | |
100 | /// if b > 10 { | |
101 | /// break b; | |
102 | /// } | |
103 | /// let c = a + b; | |
104 | /// a = b; | |
105 | /// b = c; | |
106 | /// }; | |
107 | /// // first number in Fibonacci sequence over 10: | |
108 | /// assert_eq!(result, 13); | |
5e7ed085 | 109 | /// println!("{result}"); |
e74abb32 XL |
110 | /// ``` |
111 | /// | |
112 | /// For more details consult the [Reference on "break expression"] and the [Reference on "break and | |
113 | /// loop values"]. | |
114 | /// | |
115 | /// [Reference on "break expression"]: ../reference/expressions/loop-expr.html#break-expressions | |
116 | /// [Reference on "break and loop values"]: | |
117 | /// ../reference/expressions/loop-expr.html#break-and-loop-values | |
dfeec247 | 118 | mod break_keyword {} |
48663c56 | 119 | |
0bf4aa26 XL |
120 | #[doc(keyword = "const")] |
121 | // | |
c295e0f8 | 122 | /// Compile-time constants, compile-time evaluable functions, and raw pointers. |
29967ef6 XL |
123 | /// |
124 | /// ## Compile-time constants | |
0bf4aa26 XL |
125 | /// |
126 | /// Sometimes a certain value is used many times throughout a program, and it can become | |
127 | /// inconvenient to copy it over and over. What's more, it's not always possible or desirable to | |
128 | /// make it a variable that gets carried around to each function that needs it. In these cases, the | |
1b1a35ee | 129 | /// `const` keyword provides a convenient alternative to code duplication: |
0bf4aa26 XL |
130 | /// |
131 | /// ```rust | |
132 | /// const THING: u32 = 0xABAD1DEA; | |
133 | /// | |
134 | /// let foo = 123 + THING; | |
135 | /// ``` | |
136 | /// | |
1b1a35ee XL |
137 | /// Constants must be explicitly typed; unlike with `let`, you can't ignore their type and let the |
138 | /// compiler figure it out. Any constant value can be defined in a `const`, which in practice happens | |
139 | /// to be most things that would be reasonable to have in a constant (barring `const fn`s). For | |
140 | /// example, you can't have a [`File`] as a `const`. | |
141 | /// | |
142 | /// [`File`]: crate::fs::File | |
0bf4aa26 XL |
143 | /// |
144 | /// The only lifetime allowed in a constant is `'static`, which is the lifetime that encompasses | |
145 | /// all others in a Rust program. For example, if you wanted to define a constant string, it would | |
146 | /// look like this: | |
147 | /// | |
148 | /// ```rust | |
60c5eb7d | 149 | /// const WORDS: &'static str = "hello rust!"; |
0bf4aa26 XL |
150 | /// ``` |
151 | /// | |
1b1a35ee | 152 | /// Thanks to static lifetime elision, you usually don't have to explicitly use `'static`: |
0bf4aa26 XL |
153 | /// |
154 | /// ```rust | |
155 | /// const WORDS: &str = "hello convenience!"; | |
156 | /// ``` | |
157 | /// | |
158 | /// `const` items looks remarkably similar to `static` items, which introduces some confusion as | |
159 | /// to which one should be used at which times. To put it simply, constants are inlined wherever | |
1b1a35ee XL |
160 | /// they're used, making using them identical to simply replacing the name of the `const` with its |
161 | /// value. Static variables, on the other hand, point to a single location in memory, which all | |
0bf4aa26 XL |
162 | /// accesses share. This means that, unlike with constants, they can't have destructors, and act as |
163 | /// a single value across the entire codebase. | |
164 | /// | |
1b1a35ee | 165 | /// Constants, like statics, should always be in `SCREAMING_SNAKE_CASE`. |
0bf4aa26 | 166 | /// |
29967ef6 XL |
167 | /// For more detail on `const`, see the [Rust Book] or the [Reference]. |
168 | /// | |
169 | /// ## Compile-time evaluable functions | |
170 | /// | |
171 | /// The other main use of the `const` keyword is in `const fn`. This marks a function as being | |
172 | /// callable in the body of a `const` or `static` item and in array initializers (commonly called | |
173 | /// "const contexts"). `const fn` are restricted in the set of operations they can perform, to | |
174 | /// ensure that they can be evaluated at compile-time. See the [Reference][const-eval] for more | |
175 | /// detail. | |
176 | /// | |
177 | /// Turning a `fn` into a `const fn` has no effect on run-time uses of that function. | |
178 | /// | |
179 | /// ## Other uses of `const` | |
180 | /// | |
0bf4aa26 | 181 | /// The `const` keyword is also used in raw pointers in combination with `mut`, as seen in `*const |
1b1a35ee | 182 | /// T` and `*mut T`. More about `const` as used in raw pointers can be read at the Rust docs for the [pointer primitive]. |
0bf4aa26 | 183 | /// |
6a06907d | 184 | /// [pointer primitive]: pointer |
3c0e092e | 185 | /// [Rust Book]: ../book/ch03-01-variables-and-mutability.html#constants |
48663c56 | 186 | /// [Reference]: ../reference/items/constant-items.html |
29967ef6 | 187 | /// [const-eval]: ../reference/const_eval.html |
dfeec247 | 188 | mod const_keyword {} |
0bf4aa26 | 189 | |
48663c56 XL |
190 | #[doc(keyword = "continue")] |
191 | // | |
192 | /// Skip to the next iteration of a loop. | |
193 | /// | |
e74abb32 XL |
194 | /// When `continue` is encountered, the current iteration is terminated, returning control to the |
195 | /// loop head, typically continuing with the next iteration. | |
196 | /// | |
923072b8 | 197 | /// ```rust |
e74abb32 XL |
198 | /// // Printing odd numbers by skipping even ones |
199 | /// for number in 1..=10 { | |
200 | /// if number % 2 == 0 { | |
201 | /// continue; | |
202 | /// } | |
5e7ed085 | 203 | /// println!("{number}"); |
e74abb32 | 204 | /// } |
923072b8 | 205 | /// ``` |
e74abb32 XL |
206 | /// |
207 | /// Like `break`, `continue` is normally associated with the innermost enclosing loop, but labels | |
208 | /// may be used to specify the affected loop. | |
209 | /// | |
923072b8 | 210 | /// ```rust |
e74abb32 XL |
211 | /// // Print Odd numbers under 30 with unit <= 5 |
212 | /// 'tens: for ten in 0..3 { | |
60c5eb7d | 213 | /// '_units: for unit in 0..=9 { |
e74abb32 XL |
214 | /// if unit % 2 == 0 { |
215 | /// continue; | |
216 | /// } | |
217 | /// if unit > 5 { | |
218 | /// continue 'tens; | |
219 | /// } | |
220 | /// println!("{}", ten * 10 + unit); | |
221 | /// } | |
222 | /// } | |
923072b8 | 223 | /// ``` |
e74abb32 XL |
224 | /// |
225 | /// See [continue expressions] from the reference for more details. | |
226 | /// | |
227 | /// [continue expressions]: ../reference/expressions/loop-expr.html#continue-expressions | |
dfeec247 | 228 | mod continue_keyword {} |
48663c56 | 229 | |
0bf4aa26 XL |
230 | #[doc(keyword = "crate")] |
231 | // | |
48663c56 | 232 | /// A Rust binary or library. |
0bf4aa26 XL |
233 | /// |
234 | /// The primary use of the `crate` keyword is as a part of `extern crate` declarations, which are | |
235 | /// used to specify a dependency on a crate external to the one it's declared in. Crates are the | |
236 | /// fundamental compilation unit of Rust code, and can be seen as libraries or projects. More can | |
237 | /// be read about crates in the [Reference]. | |
238 | /// | |
239 | /// ```rust ignore | |
240 | /// extern crate rand; | |
241 | /// extern crate my_crate as thing; | |
242 | /// extern crate std; // implicitly added to the root of every Rust project | |
243 | /// ``` | |
244 | /// | |
245 | /// The `as` keyword can be used to change what the crate is referred to as in your project. If a | |
246 | /// crate name includes a dash, it is implicitly imported with the dashes replaced by underscores. | |
247 | /// | |
416331ca | 248 | /// `crate` can also be used as in conjunction with `pub` to signify that the item it's attached to |
0bf4aa26 XL |
249 | /// is public only to other members of the same crate it's in. |
250 | /// | |
251 | /// ```rust | |
252 | /// # #[allow(unused_imports)] | |
253 | /// pub(crate) use std::io::Error as IoError; | |
254 | /// pub(crate) enum CoolMarkerType { } | |
255 | /// pub struct PublicThing { | |
256 | /// pub(crate) semi_secret_thing: bool, | |
257 | /// } | |
258 | /// ``` | |
259 | /// | |
416331ca XL |
260 | /// `crate` is also used to represent the absolute path of a module, where `crate` refers to the |
261 | /// root of the current crate. For instance, `crate::foo::bar` refers to the name `bar` inside the | |
262 | /// module `foo`, from anywhere else in the same crate. | |
263 | /// | |
48663c56 | 264 | /// [Reference]: ../reference/items/extern-crates.html |
dfeec247 | 265 | mod crate_keyword {} |
0bf4aa26 | 266 | |
48663c56 XL |
267 | #[doc(keyword = "else")] |
268 | // | |
ba9703b0 | 269 | /// What expression to evaluate when an [`if`] condition evaluates to [`false`]. |
48663c56 | 270 | /// |
ba9703b0 XL |
271 | /// `else` expressions are optional. When no else expressions are supplied it is assumed to evaluate |
272 | /// to the unit type `()`. | |
273 | /// | |
274 | /// The type that the `else` blocks evaluate to must be compatible with the type that the `if` block | |
275 | /// evaluates to. | |
276 | /// | |
277 | /// As can be seen below, `else` must be followed by either: `if`, `if let`, or a block `{}` and it | |
278 | /// will return the value of that expression. | |
279 | /// | |
280 | /// ```rust | |
281 | /// let result = if true == false { | |
282 | /// "oh no" | |
283 | /// } else if "something" == "other thing" { | |
284 | /// "oh dear" | |
285 | /// } else if let Some(200) = "blarg".parse::<i32>().ok() { | |
286 | /// "uh oh" | |
287 | /// } else { | |
288 | /// println!("Sneaky side effect."); | |
289 | /// "phew, nothing's broken" | |
290 | /// }; | |
291 | /// ``` | |
292 | /// | |
293 | /// Here's another example but here we do not try and return an expression: | |
48663c56 | 294 | /// |
ba9703b0 XL |
295 | /// ```rust |
296 | /// if true == false { | |
297 | /// println!("oh no"); | |
298 | /// } else if "something" == "other thing" { | |
299 | /// println!("oh dear"); | |
300 | /// } else if let Some(200) = "blarg".parse::<i32>().ok() { | |
301 | /// println!("uh oh"); | |
302 | /// } else { | |
303 | /// println!("phew, nothing's broken"); | |
304 | /// } | |
305 | /// ``` | |
306 | /// | |
307 | /// The above is _still_ an expression but it will always evaluate to `()`. | |
308 | /// | |
309 | /// There is possibly no limit to the number of `else` blocks that could follow an `if` expression | |
310 | /// however if you have several then a [`match`] expression might be preferable. | |
311 | /// | |
312 | /// Read more about control flow in the [Rust Book]. | |
313 | /// | |
314 | /// [Rust Book]: ../book/ch03-05-control-flow.html#handling-multiple-conditions-with-else-if | |
315 | /// [`match`]: keyword.match.html | |
316 | /// [`false`]: keyword.false.html | |
48663c56 | 317 | /// [`if`]: keyword.if.html |
dfeec247 | 318 | mod else_keyword {} |
48663c56 | 319 | |
0bf4aa26 XL |
320 | #[doc(keyword = "enum")] |
321 | // | |
48663c56 | 322 | /// A type that can be any one of several variants. |
0bf4aa26 XL |
323 | /// |
324 | /// Enums in Rust are similar to those of other compiled languages like C, but have important | |
325 | /// differences that make them considerably more powerful. What Rust calls enums are more commonly | |
48663c56 XL |
326 | /// known as [Algebraic Data Types][ADT] if you're coming from a functional programming background. |
327 | /// The important detail is that each enum variant can have data to go along with it. | |
0bf4aa26 XL |
328 | /// |
329 | /// ```rust | |
330 | /// # struct Coord; | |
331 | /// enum SimpleEnum { | |
332 | /// FirstVariant, | |
333 | /// SecondVariant, | |
334 | /// ThirdVariant, | |
335 | /// } | |
336 | /// | |
337 | /// enum Location { | |
338 | /// Unknown, | |
339 | /// Anonymous, | |
340 | /// Known(Coord), | |
341 | /// } | |
342 | /// | |
343 | /// enum ComplexEnum { | |
344 | /// Nothing, | |
345 | /// Something(u32), | |
346 | /// LotsOfThings { | |
347 | /// usual_struct_stuff: bool, | |
348 | /// blah: String, | |
349 | /// } | |
350 | /// } | |
351 | /// | |
352 | /// enum EmptyEnum { } | |
353 | /// ``` | |
354 | /// | |
355 | /// The first enum shown is the usual kind of enum you'd find in a C-style language. The second | |
356 | /// shows off a hypothetical example of something storing location data, with `Coord` being any | |
357 | /// other type that's needed, for example a struct. The third example demonstrates the kind of | |
358 | /// data a variant can store, ranging from nothing, to a tuple, to an anonymous struct. | |
359 | /// | |
360 | /// Instantiating enum variants involves explicitly using the enum's name as its namespace, | |
361 | /// followed by one of its variants. `SimpleEnum::SecondVariant` would be an example from above. | |
362 | /// When data follows along with a variant, such as with rust's built-in [`Option`] type, the data | |
363 | /// is added as the type describes, for example `Option::Some(123)`. The same follows with | |
364 | /// struct-like variants, with things looking like `ComplexEnum::LotsOfThings { usual_struct_stuff: | |
29967ef6 | 365 | /// true, blah: "hello!".to_string(), }`. Empty Enums are similar to [`!`] in that they cannot be |
0bf4aa26 XL |
366 | /// instantiated at all, and are used mainly to mess with the type system in interesting ways. |
367 | /// | |
368 | /// For more information, take a look at the [Rust Book] or the [Reference] | |
369 | /// | |
48663c56 | 370 | /// [ADT]: https://en.wikipedia.org/wiki/Algebraic_data_type |
48663c56 XL |
371 | /// [Rust Book]: ../book/ch06-01-defining-an-enum.html |
372 | /// [Reference]: ../reference/items/enumerations.html | |
dfeec247 | 373 | mod enum_keyword {} |
0bf4aa26 XL |
374 | |
375 | #[doc(keyword = "extern")] | |
376 | // | |
48663c56 | 377 | /// Link to or import external code. |
0bf4aa26 XL |
378 | /// |
379 | /// The `extern` keyword is used in two places in Rust. One is in conjunction with the [`crate`] | |
0731742a | 380 | /// keyword to make your Rust code aware of other Rust crates in your project, i.e., `extern crate |
0bf4aa26 XL |
381 | /// lazy_static;`. The other use is in foreign function interfaces (FFI). |
382 | /// | |
383 | /// `extern` is used in two different contexts within FFI. The first is in the form of external | |
384 | /// blocks, for declaring function interfaces that Rust code can call foreign code by. | |
385 | /// | |
386 | /// ```rust ignore | |
387 | /// #[link(name = "my_c_library")] | |
388 | /// extern "C" { | |
389 | /// fn my_c_function(x: i32) -> bool; | |
390 | /// } | |
391 | /// ``` | |
392 | /// | |
393 | /// This code would attempt to link with `libmy_c_library.so` on unix-like systems and | |
394 | /// `my_c_library.dll` on Windows at runtime, and panic if it can't find something to link to. Rust | |
395 | /// code could then use `my_c_function` as if it were any other unsafe Rust function. Working with | |
396 | /// non-Rust languages and FFI is inherently unsafe, so wrappers are usually built around C APIs. | |
397 | /// | |
398 | /// The mirror use case of FFI is also done via the `extern` keyword: | |
399 | /// | |
400 | /// ```rust | |
401 | /// #[no_mangle] | |
5869c6ff | 402 | /// pub extern "C" fn callable_from_c(x: i32) -> bool { |
0bf4aa26 XL |
403 | /// x % 3 == 0 |
404 | /// } | |
405 | /// ``` | |
406 | /// | |
407 | /// If compiled as a dylib, the resulting .so could then be linked to from a C library, and the | |
408 | /// function could be used as if it was from any other library. | |
409 | /// | |
410 | /// For more information on FFI, check the [Rust book] or the [Reference]. | |
411 | /// | |
412 | /// [Rust book]: | |
48663c56 XL |
413 | /// ../book/ch19-01-unsafe-rust.html#using-extern-functions-to-call-external-code |
414 | /// [Reference]: ../reference/items/external-blocks.html | |
29967ef6 | 415 | /// [`crate`]: keyword.crate.html |
dfeec247 | 416 | mod extern_keyword {} |
0bf4aa26 | 417 | |
48663c56 XL |
418 | #[doc(keyword = "false")] |
419 | // | |
420 | /// A value of type [`bool`] representing logical **false**. | |
421 | /// | |
3dfed10e XL |
422 | /// `false` is the logical opposite of [`true`]. |
423 | /// | |
424 | /// See the documentation for [`true`] for more information. | |
48663c56 | 425 | /// |
3dfed10e | 426 | /// [`true`]: keyword.true.html |
dfeec247 | 427 | mod false_keyword {} |
48663c56 | 428 | |
94b46f34 XL |
429 | #[doc(keyword = "fn")] |
430 | // | |
48663c56 | 431 | /// A function or function pointer. |
94b46f34 | 432 | /// |
0bf4aa26 XL |
433 | /// Functions are the primary way code is executed within Rust. Function blocks, usually just |
434 | /// called functions, can be defined in a variety of different places and be assigned many | |
435 | /// different attributes and modifiers. | |
94b46f34 | 436 | /// |
0bf4aa26 XL |
437 | /// Standalone functions that just sit within a module not attached to anything else are common, |
438 | /// but most functions will end up being inside [`impl`] blocks, either on another type itself, or | |
439 | /// as a trait impl for that type. | |
94b46f34 XL |
440 | /// |
441 | /// ```rust | |
0bf4aa26 XL |
442 | /// fn standalone_function() { |
443 | /// // code | |
444 | /// } | |
445 | /// | |
446 | /// pub fn public_thing(argument: bool) -> String { | |
447 | /// // code | |
448 | /// # "".to_string() | |
449 | /// } | |
450 | /// | |
451 | /// struct Thing { | |
452 | /// foo: i32, | |
453 | /// } | |
454 | /// | |
455 | /// impl Thing { | |
456 | /// pub fn new() -> Self { | |
457 | /// Self { | |
458 | /// foo: 42, | |
459 | /// } | |
460 | /// } | |
94b46f34 XL |
461 | /// } |
462 | /// ``` | |
463 | /// | |
0bf4aa26 XL |
464 | /// In addition to presenting fixed types in the form of `fn name(arg: type, ..) -> return_type`, |
465 | /// functions can also declare a list of type parameters along with trait bounds that they fall | |
466 | /// into. | |
94b46f34 | 467 | /// |
0bf4aa26 XL |
468 | /// ```rust |
469 | /// fn generic_function<T: Clone>(x: T) -> (T, T, T) { | |
470 | /// (x.clone(), x.clone(), x.clone()) | |
471 | /// } | |
472 | /// | |
473 | /// fn generic_where<T>(x: T) -> T | |
9fa01778 | 474 | /// where T: std::ops::Add<Output = T> + Copy |
0bf4aa26 XL |
475 | /// { |
476 | /// x + x + x | |
477 | /// } | |
478 | /// ``` | |
479 | /// | |
480 | /// Declaring trait bounds in the angle brackets is functionally identical to using a `where` | |
481 | /// clause. It's up to the programmer to decide which works better in each situation, but `where` | |
482 | /// tends to be better when things get longer than one line. | |
483 | /// | |
484 | /// Along with being made public via `pub`, `fn` can also have an [`extern`] added for use in | |
485 | /// FFI. | |
486 | /// | |
487 | /// For more information on the various types of functions and how they're used, consult the [Rust | |
488 | /// book] or the [Reference]. | |
489 | /// | |
490 | /// [`impl`]: keyword.impl.html | |
491 | /// [`extern`]: keyword.extern.html | |
48663c56 XL |
492 | /// [Rust book]: ../book/ch03-03-how-functions-work.html |
493 | /// [Reference]: ../reference/items/functions.html | |
dfeec247 | 494 | mod fn_keyword {} |
b7449926 | 495 | |
0bf4aa26 | 496 | #[doc(keyword = "for")] |
b7449926 | 497 | // |
48663c56 XL |
498 | /// Iteration with [`in`], trait implementation with [`impl`], or [higher-ranked trait bounds] |
499 | /// (`for<'a>`). | |
0bf4aa26 | 500 | /// |
532ac7d7 XL |
501 | /// The `for` keyword is used in many syntactic locations: |
502 | /// | |
503 | /// * `for` is used in for-in-loops (see below). | |
504 | /// * `for` is used when implementing traits as in `impl Trait for Type` (see [`impl`] for more info | |
505 | /// on that). | |
506 | /// * `for` is also used for [higher-ranked trait bounds] as in `for<'a> &'a T: PartialEq<i32>`. | |
507 | /// | |
508 | /// for-in-loops, or to be more precise, iterator loops, are a simple syntactic sugar over a common | |
3dfed10e XL |
509 | /// practice within Rust, which is to loop over anything that implements [`IntoIterator`] until the |
510 | /// iterator returned by `.into_iter()` returns `None` (or the loop body uses `break`). | |
0bf4aa26 XL |
511 | /// |
512 | /// ```rust | |
513 | /// for i in 0..5 { | |
514 | /// println!("{}", i * 2); | |
515 | /// } | |
b7449926 | 516 | /// |
0bf4aa26 | 517 | /// for i in std::iter::repeat(5) { |
5e7ed085 | 518 | /// println!("turns out {i} never stops being 5"); |
0bf4aa26 XL |
519 | /// break; // would loop forever otherwise |
520 | /// } | |
b7449926 | 521 | /// |
0bf4aa26 XL |
522 | /// 'outer: for x in 5..50 { |
523 | /// for y in 0..10 { | |
524 | /// if x == y { | |
525 | /// break 'outer; | |
526 | /// } | |
527 | /// } | |
528 | /// } | |
529 | /// ``` | |
530 | /// | |
531 | /// As shown in the example above, `for` loops (along with all other loops) can be tagged, using | |
532 | /// similar syntax to lifetimes (only visually similar, entirely distinct in practice). Giving the | |
533 | /// same tag to `break` breaks the tagged loop, which is useful for inner loops. It is definitely | |
534 | /// not a goto. | |
535 | /// | |
536 | /// A `for` loop expands as shown: | |
b7449926 XL |
537 | /// |
538 | /// ```rust | |
0bf4aa26 XL |
539 | /// # fn code() { } |
540 | /// # let iterator = 0..2; | |
541 | /// for loop_variable in iterator { | |
542 | /// code() | |
543 | /// } | |
544 | /// ``` | |
545 | /// | |
546 | /// ```rust | |
547 | /// # fn code() { } | |
548 | /// # let iterator = 0..2; | |
549 | /// { | |
cdc7bbd5 XL |
550 | /// let result = match IntoIterator::into_iter(iterator) { |
551 | /// mut iter => loop { | |
cdc7bbd5 | 552 | /// match iter.next() { |
cdc7bbd5 | 553 | /// None => break, |
3c0e092e | 554 | /// Some(loop_variable) => { code(); }, |
cdc7bbd5 | 555 | /// }; |
cdc7bbd5 XL |
556 | /// }, |
557 | /// }; | |
558 | /// result | |
0bf4aa26 XL |
559 | /// } |
560 | /// ``` | |
561 | /// | |
562 | /// More details on the functionality shown can be seen at the [`IntoIterator`] docs. | |
563 | /// | |
564 | /// For more information on for-loops, see the [Rust book] or the [Reference]. | |
565 | /// | |
fc512014 XL |
566 | /// See also, [`loop`], [`while`]. |
567 | /// | |
48663c56 | 568 | /// [`in`]: keyword.in.html |
0bf4aa26 | 569 | /// [`impl`]: keyword.impl.html |
fc512014 XL |
570 | /// [`loop`]: keyword.loop.html |
571 | /// [`while`]: keyword.while.html | |
48663c56 | 572 | /// [higher-ranked trait bounds]: ../reference/trait-bounds.html#higher-ranked-trait-bounds |
0bf4aa26 | 573 | /// [Rust book]: |
48663c56 XL |
574 | /// ../book/ch03-05-control-flow.html#looping-through-a-collection-with-for |
575 | /// [Reference]: ../reference/expressions/loop-expr.html#iterator-loops | |
dfeec247 | 576 | mod for_keyword {} |
0bf4aa26 XL |
577 | |
578 | #[doc(keyword = "if")] | |
579 | // | |
48663c56 | 580 | /// Evaluate a block if a condition holds. |
0bf4aa26 XL |
581 | /// |
582 | /// `if` is a familiar construct to most programmers, and is the main way you'll often do logic in | |
583 | /// your code. However, unlike in most languages, `if` blocks can also act as expressions. | |
584 | /// | |
585 | /// ```rust | |
586 | /// # let rude = true; | |
587 | /// if 1 == 2 { | |
588 | /// println!("whoops, mathematics broke"); | |
589 | /// } else { | |
590 | /// println!("everything's fine!"); | |
591 | /// } | |
592 | /// | |
593 | /// let greeting = if rude { | |
594 | /// "sup nerd." | |
595 | /// } else { | |
596 | /// "hello, friend!" | |
597 | /// }; | |
598 | /// | |
599 | /// if let Ok(x) = "123".parse::<i32>() { | |
600 | /// println!("{} double that and you get {}!", greeting, x * 2); | |
601 | /// } | |
602 | /// ``` | |
603 | /// | |
604 | /// Shown above are the three typical forms an `if` block comes in. First is the usual kind of | |
605 | /// thing you'd see in many languages, with an optional `else` block. Second uses `if` as an | |
606 | /// expression, which is only possible if all branches return the same type. An `if` expression can | |
607 | /// be used everywhere you'd expect. The third kind of `if` block is an `if let` block, which | |
608 | /// behaves similarly to using a `match` expression: | |
609 | /// | |
610 | /// ```rust | |
611 | /// if let Some(x) = Some(123) { | |
612 | /// // code | |
613 | /// # let _ = x; | |
614 | /// } else { | |
615 | /// // something else | |
616 | /// } | |
617 | /// | |
618 | /// match Some(123) { | |
619 | /// Some(x) => { | |
620 | /// // code | |
621 | /// # let _ = x; | |
622 | /// }, | |
623 | /// _ => { | |
624 | /// // something else | |
625 | /// }, | |
626 | /// } | |
627 | /// ``` | |
628 | /// | |
629 | /// Each kind of `if` expression can be mixed and matched as needed. | |
630 | /// | |
631 | /// ```rust | |
632 | /// if true == false { | |
633 | /// println!("oh no"); | |
634 | /// } else if "something" == "other thing" { | |
635 | /// println!("oh dear"); | |
636 | /// } else if let Some(200) = "blarg".parse::<i32>().ok() { | |
637 | /// println!("uh oh"); | |
638 | /// } else { | |
639 | /// println!("phew, nothing's broken"); | |
640 | /// } | |
641 | /// ``` | |
642 | /// | |
643 | /// The `if` keyword is used in one other place in Rust, namely as a part of pattern matching | |
644 | /// itself, allowing patterns such as `Some(x) if x > 200` to be used. | |
645 | /// | |
646 | /// For more information on `if` expressions, see the [Rust book] or the [Reference]. | |
647 | /// | |
48663c56 XL |
648 | /// [Rust book]: ../book/ch03-05-control-flow.html#if-expressions |
649 | /// [Reference]: ../reference/expressions/if-expr.html | |
dfeec247 | 650 | mod if_keyword {} |
0bf4aa26 XL |
651 | |
652 | #[doc(keyword = "impl")] | |
653 | // | |
48663c56 | 654 | /// Implement some functionality for a type. |
0bf4aa26 XL |
655 | /// |
656 | /// The `impl` keyword is primarily used to define implementations on types. Inherent | |
657 | /// implementations are standalone, while trait implementations are used to implement traits for | |
658 | /// types, or other traits. | |
659 | /// | |
660 | /// Functions and consts can both be defined in an implementation. A function defined in an | |
661 | /// `impl` block can be standalone, meaning it would be called like `Foo::bar()`. If the function | |
662 | /// takes `self`, `&self`, or `&mut self` as its first argument, it can also be called using | |
663 | /// method-call syntax, a familiar feature to any object oriented programmer, like `foo.bar()`. | |
664 | /// | |
665 | /// ```rust | |
666 | /// struct Example { | |
667 | /// number: i32, | |
668 | /// } | |
669 | /// | |
670 | /// impl Example { | |
671 | /// fn boo() { | |
672 | /// println!("boo! Example::boo() was called!"); | |
673 | /// } | |
674 | /// | |
675 | /// fn answer(&mut self) { | |
676 | /// self.number += 42; | |
677 | /// } | |
678 | /// | |
679 | /// fn get_number(&self) -> i32 { | |
680 | /// self.number | |
681 | /// } | |
682 | /// } | |
683 | /// | |
684 | /// trait Thingy { | |
685 | /// fn do_thingy(&self); | |
686 | /// } | |
687 | /// | |
688 | /// impl Thingy for Example { | |
689 | /// fn do_thingy(&self) { | |
690 | /// println!("doing a thing! also, number is {}!", self.number); | |
691 | /// } | |
692 | /// } | |
b7449926 XL |
693 | /// ``` |
694 | /// | |
0bf4aa26 | 695 | /// For more information on implementations, see the [Rust book][book1] or the [Reference]. |
b7449926 | 696 | /// |
0bf4aa26 XL |
697 | /// The other use of the `impl` keyword is in `impl Trait` syntax, which can be seen as a shorthand |
698 | /// for "a concrete type that implements this trait". Its primary use is working with closures, | |
699 | /// which have type definitions generated at compile time that can't be simply typed out. | |
700 | /// | |
701 | /// ```rust | |
702 | /// fn thing_returning_closure() -> impl Fn(i32) -> bool { | |
703 | /// println!("here's a closure for you!"); | |
704 | /// |x: i32| x % 3 == 0 | |
705 | /// } | |
706 | /// ``` | |
707 | /// | |
708 | /// For more information on `impl Trait` syntax, see the [Rust book][book2]. | |
709 | /// | |
48663c56 XL |
710 | /// [book1]: ../book/ch05-03-method-syntax.html |
711 | /// [Reference]: ../reference/items/implementations.html | |
712 | /// [book2]: ../book/ch10-02-traits.html#returning-types-that-implement-traits | |
dfeec247 | 713 | mod impl_keyword {} |
0bf4aa26 | 714 | |
48663c56 XL |
715 | #[doc(keyword = "in")] |
716 | // | |
717 | /// Iterate over a series of values with [`for`]. | |
718 | /// | |
3dfed10e | 719 | /// The expression immediately following `in` must implement the [`IntoIterator`] trait. |
ba9703b0 XL |
720 | /// |
721 | /// ## Literal Examples: | |
722 | /// | |
fc512014 XL |
723 | /// * `for _ in 1..3 {}` - Iterate over an exclusive range up to but excluding 3. |
724 | /// * `for _ in 1..=3 {}` - Iterate over an inclusive range up to and including 3. | |
ba9703b0 XL |
725 | /// |
726 | /// (Read more about [range patterns]) | |
48663c56 | 727 | /// |
3dfed10e | 728 | /// [`IntoIterator`]: ../book/ch13-04-performance.html |
f9f354fc | 729 | /// [range patterns]: ../reference/patterns.html?highlight=range#range-patterns |
48663c56 | 730 | /// [`for`]: keyword.for.html |
5e7ed085 FG |
731 | /// |
732 | /// The other use of `in` is with the keyword `pub`. It allows users to declare an item as visible | |
733 | /// only within a given scope. | |
734 | /// | |
735 | /// ## Literal Example: | |
736 | /// | |
737 | /// * `pub(in crate::outer_mod) fn outer_mod_visible_fn() {}` - fn is visible in `outer_mod` | |
738 | /// | |
739 | /// Starting with the 2018 edition, paths for `pub(in path)` must start with `crate`, `self` or | |
740 | /// `super`. The 2015 edition may also use paths starting with `::` or modules from the crate root. | |
741 | /// | |
742 | /// For more information, see the [Reference]. | |
743 | /// | |
744 | /// [Reference]: ../reference/visibility-and-privacy.html#pubin-path-pubcrate-pubsuper-and-pubself | |
dfeec247 | 745 | mod in_keyword {} |
48663c56 | 746 | |
0bf4aa26 XL |
747 | #[doc(keyword = "let")] |
748 | // | |
48663c56 | 749 | /// Bind a value to a variable. |
0bf4aa26 XL |
750 | /// |
751 | /// The primary use for the `let` keyword is in `let` statements, which are used to introduce a new | |
752 | /// set of variables into the current scope, as given by a pattern. | |
b7449926 XL |
753 | /// |
754 | /// ```rust | |
755 | /// # #![allow(unused_assignments)] | |
0bf4aa26 XL |
756 | /// let thing1: i32 = 100; |
757 | /// let thing2 = 200 + thing1; | |
758 | /// | |
759 | /// let mut changing_thing = true; | |
760 | /// changing_thing = false; | |
b7449926 | 761 | /// |
0bf4aa26 XL |
762 | /// let (part1, part2) = ("first", "second"); |
763 | /// | |
764 | /// struct Example { | |
765 | /// a: bool, | |
766 | /// b: u64, | |
767 | /// } | |
768 | /// | |
769 | /// let Example { a, b: _ } = Example { | |
770 | /// a: true, | |
771 | /// b: 10004, | |
772 | /// }; | |
773 | /// assert!(a); | |
774 | /// ``` | |
775 | /// | |
776 | /// The pattern is most commonly a single variable, which means no pattern matching is done and | |
777 | /// the expression given is bound to the variable. Apart from that, patterns used in `let` bindings | |
778 | /// can be as complicated as needed, given that the pattern is exhaustive. See the [Rust | |
779 | /// book][book1] for more information on pattern matching. The type of the pattern is optionally | |
780 | /// given afterwards, but if left blank is automatically inferred by the compiler if possible. | |
781 | /// | |
782 | /// Variables in Rust are immutable by default, and require the `mut` keyword to be made mutable. | |
783 | /// | |
784 | /// Multiple variables can be defined with the same name, known as shadowing. This doesn't affect | |
785 | /// the original variable in any way beyond being unable to directly access it beyond the point of | |
786 | /// shadowing. It continues to remain in scope, getting dropped only when it falls out of scope. | |
787 | /// Shadowed variables don't need to have the same type as the variables shadowing them. | |
788 | /// | |
789 | /// ```rust | |
790 | /// let shadowing_example = true; | |
791 | /// let shadowing_example = 123.4; | |
792 | /// let shadowing_example = shadowing_example as u32; | |
5e7ed085 | 793 | /// let mut shadowing_example = format!("cool! {shadowing_example}"); |
0bf4aa26 | 794 | /// shadowing_example += " something else!"; // not shadowing |
b7449926 XL |
795 | /// ``` |
796 | /// | |
0bf4aa26 XL |
797 | /// Other places the `let` keyword is used include along with [`if`], in the form of `if let` |
798 | /// expressions. They're useful if the pattern being matched isn't exhaustive, such as with | |
799 | /// enumerations. `while let` also exists, which runs a loop with a pattern matched value until | |
800 | /// that pattern can't be matched. | |
b7449926 | 801 | /// |
48663c56 | 802 | /// For more information on the `let` keyword, see the [Rust book][book2] or the [Reference] |
0bf4aa26 | 803 | /// |
48663c56 | 804 | /// [book1]: ../book/ch06-02-match.html |
0bf4aa26 | 805 | /// [`if`]: keyword.if.html |
48663c56 XL |
806 | /// [book2]: ../book/ch18-01-all-the-places-for-patterns.html#let-statements |
807 | /// [Reference]: ../reference/statements.html#let-statements | |
dfeec247 | 808 | mod let_keyword {} |
b7449926 | 809 | |
416331ca XL |
810 | #[doc(keyword = "while")] |
811 | // | |
812 | /// Loop while a condition is upheld. | |
813 | /// | |
814 | /// A `while` expression is used for predicate loops. The `while` expression runs the conditional | |
815 | /// expression before running the loop body, then runs the loop body if the conditional | |
816 | /// expression evaluates to `true`, or exits the loop otherwise. | |
817 | /// | |
818 | /// ```rust | |
819 | /// let mut counter = 0; | |
820 | /// | |
821 | /// while counter < 10 { | |
5e7ed085 | 822 | /// println!("{counter}"); |
416331ca XL |
823 | /// counter += 1; |
824 | /// } | |
825 | /// ``` | |
826 | /// | |
827 | /// Like the [`for`] expression, we can use `break` and `continue`. A `while` expression | |
828 | /// cannot break with a value and always evaluates to `()` unlike [`loop`]. | |
829 | /// | |
830 | /// ```rust | |
831 | /// let mut i = 1; | |
832 | /// | |
833 | /// while i < 100 { | |
834 | /// i *= 2; | |
835 | /// if i == 64 { | |
836 | /// break; // Exit when `i` is 64. | |
837 | /// } | |
838 | /// } | |
839 | /// ``` | |
840 | /// | |
841 | /// As `if` expressions have their pattern matching variant in `if let`, so too do `while` | |
842 | /// expressions with `while let`. The `while let` expression matches the pattern against the | |
843 | /// expression, then runs the loop body if pattern matching succeeds, or exits the loop otherwise. | |
844 | /// We can use `break` and `continue` in `while let` expressions just like in `while`. | |
845 | /// | |
846 | /// ```rust | |
847 | /// let mut counter = Some(0); | |
848 | /// | |
849 | /// while let Some(i) = counter { | |
850 | /// if i == 10 { | |
851 | /// counter = None; | |
852 | /// } else { | |
5e7ed085 | 853 | /// println!("{i}"); |
416331ca XL |
854 | /// counter = Some (i + 1); |
855 | /// } | |
856 | /// } | |
857 | /// ``` | |
858 | /// | |
859 | /// For more information on `while` and loops in general, see the [reference]. | |
860 | /// | |
fc512014 XL |
861 | /// See also, [`for`], [`loop`]. |
862 | /// | |
416331ca XL |
863 | /// [`for`]: keyword.for.html |
864 | /// [`loop`]: keyword.loop.html | |
865 | /// [reference]: ../reference/expressions/loop-expr.html#predicate-loops | |
dfeec247 | 866 | mod while_keyword {} |
416331ca | 867 | |
0bf4aa26 | 868 | #[doc(keyword = "loop")] |
b7449926 | 869 | // |
48663c56 | 870 | /// Loop indefinitely. |
b7449926 | 871 | /// |
0bf4aa26 XL |
872 | /// `loop` is used to define the simplest kind of loop supported in Rust. It runs the code inside |
873 | /// it until the code uses `break` or the program exits. | |
b7449926 | 874 | /// |
0bf4aa26 XL |
875 | /// ```rust |
876 | /// loop { | |
877 | /// println!("hello world forever!"); | |
878 | /// # break; | |
879 | /// } | |
b7449926 | 880 | /// |
e1599b0c | 881 | /// let mut i = 1; |
0bf4aa26 | 882 | /// loop { |
5e7ed085 | 883 | /// println!("i is {i}"); |
e1599b0c | 884 | /// if i > 100 { |
0bf4aa26 XL |
885 | /// break; |
886 | /// } | |
e1599b0c | 887 | /// i *= 2; |
0bf4aa26 | 888 | /// } |
e1599b0c | 889 | /// assert_eq!(i, 128); |
b7449926 | 890 | /// ``` |
0bf4aa26 XL |
891 | /// |
892 | /// Unlike the other kinds of loops in Rust (`while`, `while let`, and `for`), loops can be used as | |
893 | /// expressions that return values via `break`. | |
894 | /// | |
895 | /// ```rust | |
896 | /// let mut i = 1; | |
897 | /// let something = loop { | |
898 | /// i *= 2; | |
899 | /// if i > 100 { | |
900 | /// break i; | |
901 | /// } | |
902 | /// }; | |
903 | /// assert_eq!(something, 128); | |
904 | /// ``` | |
905 | /// | |
906 | /// Every `break` in a loop has to have the same type. When it's not explicitly giving something, | |
907 | /// `break;` returns `()`. | |
908 | /// | |
909 | /// For more information on `loop` and loops in general, see the [Reference]. | |
910 | /// | |
fc512014 XL |
911 | /// See also, [`for`], [`while`]. |
912 | /// | |
913 | /// [`for`]: keyword.for.html | |
914 | /// [`while`]: keyword.while.html | |
48663c56 | 915 | /// [Reference]: ../reference/expressions/loop-expr.html |
dfeec247 | 916 | mod loop_keyword {} |
0bf4aa26 | 917 | |
48663c56 XL |
918 | #[doc(keyword = "match")] |
919 | // | |
920 | /// Control flow based on pattern matching. | |
921 | /// | |
60c5eb7d XL |
922 | /// `match` can be used to run code conditionally. Every pattern must |
923 | /// be handled exhaustively either explicitly or by using wildcards like | |
924 | /// `_` in the `match`. Since `match` is an expression, values can also be | |
925 | /// returned. | |
48663c56 | 926 | /// |
60c5eb7d XL |
927 | /// ```rust |
928 | /// let opt = Option::None::<usize>; | |
929 | /// let x = match opt { | |
930 | /// Some(int) => int, | |
931 | /// None => 10, | |
932 | /// }; | |
933 | /// assert_eq!(x, 10); | |
934 | /// | |
935 | /// let a_number = Option::Some(10); | |
936 | /// match a_number { | |
5e7ed085 FG |
937 | /// Some(x) if x <= 5 => println!("0 to 5 num = {x}"), |
938 | /// Some(x @ 6..=10) => println!("6 to 10 num = {x}"), | |
60c5eb7d XL |
939 | /// None => panic!(), |
940 | /// // all other numbers | |
941 | /// _ => panic!(), | |
942 | /// } | |
943 | /// ``` | |
944 | /// | |
945 | /// `match` can be used to gain access to the inner members of an enum | |
946 | /// and use them directly. | |
947 | /// | |
948 | /// ```rust | |
949 | /// enum Outer { | |
950 | /// Double(Option<u8>, Option<String>), | |
951 | /// Single(Option<u8>), | |
952 | /// Empty | |
953 | /// } | |
954 | /// | |
955 | /// let get_inner = Outer::Double(None, Some(String::new())); | |
956 | /// match get_inner { | |
5e7ed085 FG |
957 | /// Outer::Double(None, Some(st)) => println!("{st}"), |
958 | /// Outer::Single(opt) => println!("{opt:?}"), | |
60c5eb7d XL |
959 | /// _ => panic!(), |
960 | /// } | |
961 | /// ``` | |
962 | /// | |
963 | /// For more information on `match` and matching in general, see the [Reference]. | |
964 | /// | |
965 | /// [Reference]: ../reference/expressions/match-expr.html | |
dfeec247 | 966 | mod match_keyword {} |
48663c56 XL |
967 | |
968 | #[doc(keyword = "mod")] | |
969 | // | |
970 | /// Organize code into [modules]. | |
971 | /// | |
f035d41b XL |
972 | /// Use `mod` to create new [modules] to encapsulate code, including other |
973 | /// modules: | |
974 | /// | |
975 | /// ``` | |
976 | /// mod foo { | |
977 | /// mod bar { | |
978 | /// type MyType = (u8, u8); | |
979 | /// fn baz() {} | |
980 | /// } | |
981 | /// } | |
982 | /// ``` | |
983 | /// | |
984 | /// Like [`struct`]s and [`enum`]s, a module and its content are private by | |
136023e0 | 985 | /// default, inaccessible to code outside of the module. |
48663c56 | 986 | /// |
f035d41b XL |
987 | /// To learn more about allowing access, see the documentation for the [`pub`] |
988 | /// keyword. | |
989 | /// | |
990 | /// [`enum`]: keyword.enum.html | |
991 | /// [`pub`]: keyword.pub.html | |
992 | /// [`struct`]: keyword.struct.html | |
48663c56 | 993 | /// [modules]: ../reference/items/modules.html |
dfeec247 | 994 | mod mod_keyword {} |
48663c56 XL |
995 | |
996 | #[doc(keyword = "move")] | |
997 | // | |
998 | /// Capture a [closure]'s environment by value. | |
999 | /// | |
60c5eb7d | 1000 | /// `move` converts any variables captured by reference or mutable reference |
17df50a5 | 1001 | /// to variables captured by value. |
48663c56 | 1002 | /// |
60c5eb7d | 1003 | /// ```rust |
17df50a5 | 1004 | /// let data = vec![1, 2, 3]; |
5e7ed085 | 1005 | /// let closure = move || println!("captured {data:?} by value"); |
17df50a5 XL |
1006 | /// |
1007 | /// // data is no longer available, it is owned by the closure | |
60c5eb7d XL |
1008 | /// ``` |
1009 | /// | |
3dfed10e XL |
1010 | /// Note: `move` closures may still implement [`Fn`] or [`FnMut`], even though |
1011 | /// they capture variables by `move`. This is because the traits implemented by | |
1012 | /// a closure type are determined by *what* the closure does with captured | |
1013 | /// values, not *how* it captures them: | |
1014 | /// | |
1015 | /// ```rust | |
1016 | /// fn create_fn() -> impl Fn() { | |
1017 | /// let text = "Fn".to_owned(); | |
5e7ed085 | 1018 | /// move || println!("This is a: {text}") |
3dfed10e XL |
1019 | /// } |
1020 | /// | |
17df50a5 XL |
1021 | /// let fn_plain = create_fn(); |
1022 | /// fn_plain(); | |
3dfed10e XL |
1023 | /// ``` |
1024 | /// | |
60c5eb7d XL |
1025 | /// `move` is often used when [threads] are involved. |
1026 | /// | |
1027 | /// ```rust | |
17df50a5 | 1028 | /// let data = vec![1, 2, 3]; |
60c5eb7d XL |
1029 | /// |
1030 | /// std::thread::spawn(move || { | |
5e7ed085 | 1031 | /// println!("captured {data:?} by value") |
60c5eb7d XL |
1032 | /// }).join().unwrap(); |
1033 | /// | |
17df50a5 | 1034 | /// // data was moved to the spawned thread, so we cannot use it here |
60c5eb7d XL |
1035 | /// ``` |
1036 | /// | |
74b04a01 XL |
1037 | /// `move` is also valid before an async block. |
1038 | /// | |
1039 | /// ```rust | |
17df50a5 | 1040 | /// let capture = "hello".to_owned(); |
74b04a01 | 1041 | /// let block = async move { |
5e7ed085 | 1042 | /// println!("rust says {capture} from async block"); |
74b04a01 XL |
1043 | /// }; |
1044 | /// ``` | |
1045 | /// | |
cdc7bbd5 XL |
1046 | /// For more information on the `move` keyword, see the [closures][closure] section |
1047 | /// of the Rust book or the [threads] section. | |
60c5eb7d | 1048 | /// |
60c5eb7d XL |
1049 | /// [closure]: ../book/ch13-01-closures.html |
1050 | /// [threads]: ../book/ch16-01-threads.html#using-move-closures-with-threads | |
dfeec247 | 1051 | mod move_keyword {} |
48663c56 XL |
1052 | |
1053 | #[doc(keyword = "mut")] | |
1054 | // | |
f035d41b | 1055 | /// A mutable variable, reference, or pointer. |
48663c56 | 1056 | /// |
f035d41b XL |
1057 | /// `mut` can be used in several situations. The first is mutable variables, |
1058 | /// which can be used anywhere you can bind a value to a variable name. Some | |
1059 | /// examples: | |
48663c56 | 1060 | /// |
f035d41b XL |
1061 | /// ```rust |
1062 | /// // A mutable variable in the parameter list of a function. | |
1063 | /// fn foo(mut x: u8, y: u8) -> u8 { | |
1064 | /// x += y; | |
1065 | /// x | |
1066 | /// } | |
1067 | /// | |
1068 | /// // Modifying a mutable variable. | |
1069 | /// # #[allow(unused_assignments)] | |
1070 | /// let mut a = 5; | |
1071 | /// a = 6; | |
1072 | /// | |
1073 | /// assert_eq!(foo(3, 4), 7); | |
1074 | /// assert_eq!(a, 6); | |
1075 | /// ``` | |
1076 | /// | |
1077 | /// The second is mutable references. They can be created from `mut` variables | |
1078 | /// and must be unique: no other variables can have a mutable reference, nor a | |
1079 | /// shared reference. | |
1080 | /// | |
1081 | /// ```rust | |
1082 | /// // Taking a mutable reference. | |
1083 | /// fn push_two(v: &mut Vec<u8>) { | |
1084 | /// v.push(2); | |
1085 | /// } | |
1086 | /// | |
1087 | /// // A mutable reference cannot be taken to a non-mutable variable. | |
1088 | /// let mut v = vec![0, 1]; | |
1089 | /// // Passing a mutable reference. | |
1090 | /// push_two(&mut v); | |
1091 | /// | |
1092 | /// assert_eq!(v, vec![0, 1, 2]); | |
1093 | /// ``` | |
1094 | /// | |
1095 | /// ```rust,compile_fail,E0502 | |
1096 | /// let mut v = vec![0, 1]; | |
1097 | /// let mut_ref_v = &mut v; | |
1098 | /// ##[allow(unused)] | |
1099 | /// let ref_v = &v; | |
1100 | /// mut_ref_v.push(2); | |
1101 | /// ``` | |
1102 | /// | |
1103 | /// Mutable raw pointers work much like mutable references, with the added | |
1104 | /// possibility of not pointing to a valid object. The syntax is `*mut Type`. | |
1105 | /// | |
136023e0 | 1106 | /// More information on mutable references and pointers can be found in the [Reference]. |
f035d41b XL |
1107 | /// |
1108 | /// [Reference]: ../reference/types/pointer.html#mutable-references-mut | |
dfeec247 | 1109 | mod mut_keyword {} |
48663c56 XL |
1110 | |
1111 | #[doc(keyword = "pub")] | |
1112 | // | |
1113 | /// Make an item visible to others. | |
1114 | /// | |
ba9703b0 XL |
1115 | /// The keyword `pub` makes any module, function, or data structure accessible from inside |
1116 | /// of external modules. The `pub` keyword may also be used in a `use` declaration to re-export | |
1117 | /// an identifier from a namespace. | |
48663c56 | 1118 | /// |
ba9703b0 XL |
1119 | /// For more information on the `pub` keyword, please see the visibility section |
1120 | /// of the [reference] and for some examples, see [Rust by Example]. | |
1121 | /// | |
1122 | /// [reference]:../reference/visibility-and-privacy.html?highlight=pub#visibility-and-privacy | |
1123 | /// [Rust by Example]:../rust-by-example/mod/visibility.html | |
dfeec247 | 1124 | mod pub_keyword {} |
48663c56 XL |
1125 | |
1126 | #[doc(keyword = "ref")] | |
1127 | // | |
1128 | /// Bind by reference during pattern matching. | |
1129 | /// | |
3dfed10e XL |
1130 | /// `ref` annotates pattern bindings to make them borrow rather than move. |
1131 | /// It is **not** a part of the pattern as far as matching is concerned: it does | |
1132 | /// not affect *whether* a value is matched, only *how* it is matched. | |
48663c56 | 1133 | /// |
3dfed10e XL |
1134 | /// By default, [`match`] statements consume all they can, which can sometimes |
1135 | /// be a problem, when you don't really need the value to be moved and owned: | |
1136 | /// | |
1137 | /// ```compile_fail,E0382 | |
1138 | /// let maybe_name = Some(String::from("Alice")); | |
1139 | /// // The variable 'maybe_name' is consumed here ... | |
1140 | /// match maybe_name { | |
5e7ed085 | 1141 | /// Some(n) => println!("Hello, {n}"), |
3dfed10e XL |
1142 | /// _ => println!("Hello, world"), |
1143 | /// } | |
1144 | /// // ... and is now unavailable. | |
1145 | /// println!("Hello again, {}", maybe_name.unwrap_or("world".into())); | |
1146 | /// ``` | |
1147 | /// | |
1148 | /// Using the `ref` keyword, the value is only borrowed, not moved, making it | |
1149 | /// available for use after the [`match`] statement: | |
1150 | /// | |
1151 | /// ``` | |
1152 | /// let maybe_name = Some(String::from("Alice")); | |
1153 | /// // Using `ref`, the value is borrowed, not moved ... | |
1154 | /// match maybe_name { | |
5e7ed085 | 1155 | /// Some(ref n) => println!("Hello, {n}"), |
3dfed10e XL |
1156 | /// _ => println!("Hello, world"), |
1157 | /// } | |
1158 | /// // ... so it's available here! | |
1159 | /// println!("Hello again, {}", maybe_name.unwrap_or("world".into())); | |
1160 | /// ``` | |
1161 | /// | |
1162 | /// # `&` vs `ref` | |
1163 | /// | |
1164 | /// - `&` denotes that your pattern expects a reference to an object. Hence `&` | |
1165 | /// is a part of said pattern: `&Foo` matches different objects than `Foo` does. | |
1166 | /// | |
1167 | /// - `ref` indicates that you want a reference to an unpacked value. It is not | |
1168 | /// matched against: `Foo(ref foo)` matches the same objects as `Foo(foo)`. | |
1169 | /// | |
1170 | /// See also the [Reference] for more information. | |
1171 | /// | |
1172 | /// [`match`]: keyword.match.html | |
1173 | /// [Reference]: ../reference/patterns.html#identifier-patterns | |
dfeec247 | 1174 | mod ref_keyword {} |
48663c56 XL |
1175 | |
1176 | #[doc(keyword = "return")] | |
1177 | // | |
1178 | /// Return a value from a function. | |
1179 | /// | |
f035d41b | 1180 | /// A `return` marks the end of an execution path in a function: |
48663c56 | 1181 | /// |
f035d41b XL |
1182 | /// ``` |
1183 | /// fn foo() -> i32 { | |
1184 | /// return 3; | |
1185 | /// } | |
1186 | /// assert_eq!(foo(), 3); | |
1187 | /// ``` | |
1188 | /// | |
1189 | /// `return` is not needed when the returned value is the last expression in the | |
1190 | /// function. In this case the `;` is omitted: | |
1191 | /// | |
1192 | /// ``` | |
1193 | /// fn foo() -> i32 { | |
1194 | /// 3 | |
1195 | /// } | |
1196 | /// assert_eq!(foo(), 3); | |
1197 | /// ``` | |
1198 | /// | |
1199 | /// `return` returns from the function immediately (an "early return"): | |
1200 | /// | |
1201 | /// ```no_run | |
1202 | /// use std::fs::File; | |
1203 | /// use std::io::{Error, ErrorKind, Read, Result}; | |
1204 | /// | |
1205 | /// fn main() -> Result<()> { | |
1206 | /// let mut file = match File::open("foo.txt") { | |
1207 | /// Ok(f) => f, | |
1208 | /// Err(e) => return Err(e), | |
1209 | /// }; | |
1210 | /// | |
1211 | /// let mut contents = String::new(); | |
1212 | /// let size = match file.read_to_string(&mut contents) { | |
1213 | /// Ok(s) => s, | |
1214 | /// Err(e) => return Err(e), | |
1215 | /// }; | |
1216 | /// | |
1217 | /// if contents.contains("impossible!") { | |
1218 | /// return Err(Error::new(ErrorKind::Other, "oh no!")); | |
1219 | /// } | |
1220 | /// | |
1221 | /// if size > 9000 { | |
1222 | /// return Err(Error::new(ErrorKind::Other, "over 9000!")); | |
1223 | /// } | |
1224 | /// | |
1225 | /// assert_eq!(contents, "Hello, world!"); | |
1226 | /// Ok(()) | |
1227 | /// } | |
1228 | /// ``` | |
dfeec247 | 1229 | mod return_keyword {} |
48663c56 XL |
1230 | |
1231 | #[doc(keyword = "self")] | |
1232 | // | |
1233 | /// The receiver of a method, or the current module. | |
1234 | /// | |
f035d41b XL |
1235 | /// `self` is used in two situations: referencing the current module and marking |
1236 | /// the receiver of a method. | |
48663c56 | 1237 | /// |
f035d41b XL |
1238 | /// In paths, `self` can be used to refer to the current module, either in a |
1239 | /// [`use`] statement or in a path to access an element: | |
1240 | /// | |
1241 | /// ``` | |
1242 | /// # #![allow(unused_imports)] | |
1243 | /// use std::io::{self, Read}; | |
1244 | /// ``` | |
1245 | /// | |
1246 | /// Is functionally the same as: | |
1247 | /// | |
1248 | /// ``` | |
1249 | /// # #![allow(unused_imports)] | |
1250 | /// use std::io; | |
1251 | /// use std::io::Read; | |
1252 | /// ``` | |
1253 | /// | |
1254 | /// Using `self` to access an element in the current module: | |
1255 | /// | |
1256 | /// ``` | |
1257 | /// # #![allow(dead_code)] | |
1258 | /// # fn main() {} | |
1259 | /// fn foo() {} | |
1260 | /// fn bar() { | |
1261 | /// self::foo() | |
1262 | /// } | |
1263 | /// ``` | |
1264 | /// | |
1265 | /// `self` as the current receiver for a method allows to omit the parameter | |
1266 | /// type most of the time. With the exception of this particularity, `self` is | |
1267 | /// used much like any other parameter: | |
1268 | /// | |
1269 | /// ``` | |
1270 | /// struct Foo(i32); | |
1271 | /// | |
1272 | /// impl Foo { | |
1273 | /// // No `self`. | |
1274 | /// fn new() -> Self { | |
1275 | /// Self(0) | |
1276 | /// } | |
1277 | /// | |
1278 | /// // Consuming `self`. | |
1279 | /// fn consume(self) -> Self { | |
1280 | /// Self(self.0 + 1) | |
1281 | /// } | |
1282 | /// | |
1283 | /// // Borrowing `self`. | |
1284 | /// fn borrow(&self) -> &i32 { | |
1285 | /// &self.0 | |
1286 | /// } | |
1287 | /// | |
1288 | /// // Borrowing `self` mutably. | |
1289 | /// fn borrow_mut(&mut self) -> &mut i32 { | |
1290 | /// &mut self.0 | |
1291 | /// } | |
1292 | /// } | |
1293 | /// | |
1294 | /// // This method must be called with a `Type::` prefix. | |
1295 | /// let foo = Foo::new(); | |
1296 | /// assert_eq!(foo.0, 0); | |
1297 | /// | |
1298 | /// // Those two calls produces the same result. | |
1299 | /// let foo = Foo::consume(foo); | |
1300 | /// assert_eq!(foo.0, 1); | |
1301 | /// let foo = foo.consume(); | |
1302 | /// assert_eq!(foo.0, 2); | |
1303 | /// | |
1304 | /// // Borrowing is handled automatically with the second syntax. | |
1305 | /// let borrow_1 = Foo::borrow(&foo); | |
1306 | /// let borrow_2 = foo.borrow(); | |
1307 | /// assert_eq!(borrow_1, borrow_2); | |
1308 | /// | |
1309 | /// // Borrowing mutably is handled automatically too with the second syntax. | |
1310 | /// let mut foo = Foo::new(); | |
1311 | /// *Foo::borrow_mut(&mut foo) += 1; | |
1312 | /// assert_eq!(foo.0, 1); | |
1313 | /// *foo.borrow_mut() += 1; | |
1314 | /// assert_eq!(foo.0, 2); | |
1315 | /// ``` | |
1316 | /// | |
1317 | /// Note that this automatic conversion when calling `foo.method()` is not | |
1318 | /// limited to the examples above. See the [Reference] for more information. | |
1319 | /// | |
1320 | /// [`use`]: keyword.use.html | |
1321 | /// [Reference]: ../reference/items/associated-items.html#methods | |
dfeec247 | 1322 | mod self_keyword {} |
48663c56 | 1323 | |
36d6ef2b XL |
1324 | // FIXME: Once rustdoc can handle URL conflicts on case insensitive file systems, we can remove the |
1325 | // three next lines and put back: `#[doc(keyword = "Self")]`. | |
1326 | #[doc(alias = "Self")] | |
1327 | #[allow(rustc::existing_doc_keyword)] | |
1328 | #[doc(keyword = "SelfTy")] | |
48663c56 XL |
1329 | // |
1330 | /// The implementing type within a [`trait`] or [`impl`] block, or the current type within a type | |
1331 | /// definition. | |
1332 | /// | |
f035d41b XL |
1333 | /// Within a type definition: |
1334 | /// | |
1335 | /// ``` | |
1336 | /// # #![allow(dead_code)] | |
1337 | /// struct Node { | |
1338 | /// elem: i32, | |
1339 | /// // `Self` is a `Node` here. | |
1340 | /// next: Option<Box<Self>>, | |
1341 | /// } | |
1342 | /// ``` | |
1343 | /// | |
1344 | /// In an [`impl`] block: | |
1345 | /// | |
1346 | /// ``` | |
1347 | /// struct Foo(i32); | |
1348 | /// | |
1349 | /// impl Foo { | |
1350 | /// fn new() -> Self { | |
1351 | /// Self(0) | |
1352 | /// } | |
1353 | /// } | |
1354 | /// | |
1355 | /// assert_eq!(Foo::new().0, Foo(0).0); | |
1356 | /// ``` | |
1357 | /// | |
1358 | /// Generic parameters are implicit with `Self`: | |
1359 | /// | |
1360 | /// ``` | |
1361 | /// # #![allow(dead_code)] | |
1362 | /// struct Wrap<T> { | |
1363 | /// elem: T, | |
1364 | /// } | |
1365 | /// | |
1366 | /// impl<T> Wrap<T> { | |
1367 | /// fn new(elem: T) -> Self { | |
1368 | /// Self { elem } | |
1369 | /// } | |
1370 | /// } | |
1371 | /// ``` | |
1372 | /// | |
1373 | /// In a [`trait`] definition and related [`impl`] block: | |
1374 | /// | |
1375 | /// ``` | |
1376 | /// trait Example { | |
1377 | /// fn example() -> Self; | |
1378 | /// } | |
1379 | /// | |
1380 | /// struct Foo(i32); | |
1381 | /// | |
1382 | /// impl Example for Foo { | |
1383 | /// fn example() -> Self { | |
1384 | /// Self(42) | |
1385 | /// } | |
1386 | /// } | |
1387 | /// | |
1388 | /// assert_eq!(Foo::example().0, Foo(42).0); | |
1389 | /// ``` | |
48663c56 XL |
1390 | /// |
1391 | /// [`impl`]: keyword.impl.html | |
1392 | /// [`trait`]: keyword.trait.html | |
dfeec247 | 1393 | mod self_upper_keyword {} |
48663c56 XL |
1394 | |
1395 | #[doc(keyword = "static")] | |
1396 | // | |
f035d41b XL |
1397 | /// A static item is a value which is valid for the entire duration of your |
1398 | /// program (a `'static` lifetime). | |
48663c56 | 1399 | /// |
f035d41b XL |
1400 | /// On the surface, `static` items seem very similar to [`const`]s: both contain |
1401 | /// a value, both require type annotations and both can only be initialized with | |
1402 | /// constant functions and values. However, `static`s are notably different in | |
1403 | /// that they represent a location in memory. That means that you can have | |
1404 | /// references to `static` items and potentially even modify them, making them | |
1405 | /// essentially global variables. | |
48663c56 | 1406 | /// |
f035d41b XL |
1407 | /// Static items do not call [`drop`] at the end of the program. |
1408 | /// | |
1409 | /// There are two types of `static` items: those declared in association with | |
1410 | /// the [`mut`] keyword and those without. | |
1411 | /// | |
1412 | /// Static items cannot be moved: | |
1413 | /// | |
1414 | /// ```rust,compile_fail,E0507 | |
1415 | /// static VEC: Vec<u32> = vec![]; | |
1416 | /// | |
1417 | /// fn move_vec(v: Vec<u32>) -> Vec<u32> { | |
1418 | /// v | |
1419 | /// } | |
1420 | /// | |
1421 | /// // This line causes an error | |
1422 | /// move_vec(VEC); | |
1423 | /// ``` | |
1424 | /// | |
1425 | /// # Simple `static`s | |
1426 | /// | |
1427 | /// Accessing non-[`mut`] `static` items is considered safe, but some | |
1428 | /// restrictions apply. Most notably, the type of a `static` value needs to | |
1429 | /// implement the [`Sync`] trait, ruling out interior mutability containers | |
1430 | /// like [`RefCell`]. See the [Reference] for more information. | |
1431 | /// | |
1432 | /// ```rust | |
1433 | /// static FOO: [i32; 5] = [1, 2, 3, 4, 5]; | |
1434 | /// | |
1435 | /// let r1 = &FOO as *const _; | |
1436 | /// let r2 = &FOO as *const _; | |
3dfed10e | 1437 | /// // With a strictly read-only static, references will have the same address |
f035d41b XL |
1438 | /// assert_eq!(r1, r2); |
1439 | /// // A static item can be used just like a variable in many cases | |
5e7ed085 | 1440 | /// println!("{FOO:?}"); |
f035d41b XL |
1441 | /// ``` |
1442 | /// | |
1443 | /// # Mutable `static`s | |
1444 | /// | |
1445 | /// If a `static` item is declared with the [`mut`] keyword, then it is allowed | |
1446 | /// to be modified by the program. However, accessing mutable `static`s can | |
1447 | /// cause undefined behavior in a number of ways, for example due to data races | |
1448 | /// in a multithreaded context. As such, all accesses to mutable `static`s | |
1449 | /// require an [`unsafe`] block. | |
1450 | /// | |
1451 | /// Despite their unsafety, mutable `static`s are necessary in many contexts: | |
1452 | /// they can be used to represent global state shared by the whole program or in | |
1453 | /// [`extern`] blocks to bind to variables from C libraries. | |
1454 | /// | |
1455 | /// In an [`extern`] block: | |
1456 | /// | |
1457 | /// ```rust,no_run | |
1458 | /// # #![allow(dead_code)] | |
1459 | /// extern "C" { | |
1460 | /// static mut ERROR_MESSAGE: *mut std::os::raw::c_char; | |
1461 | /// } | |
1462 | /// ``` | |
1463 | /// | |
1464 | /// Mutable `static`s, just like simple `static`s, have some restrictions that | |
1465 | /// apply to them. See the [Reference] for more information. | |
1466 | /// | |
1467 | /// [`const`]: keyword.const.html | |
1468 | /// [`extern`]: keyword.extern.html | |
1469 | /// [`mut`]: keyword.mut.html | |
1470 | /// [`unsafe`]: keyword.unsafe.html | |
3dfed10e | 1471 | /// [`RefCell`]: cell::RefCell |
f035d41b | 1472 | /// [Reference]: ../reference/items/static-items.html |
dfeec247 | 1473 | mod static_keyword {} |
48663c56 | 1474 | |
0bf4aa26 XL |
1475 | #[doc(keyword = "struct")] |
1476 | // | |
48663c56 | 1477 | /// A type that is composed of other types. |
0bf4aa26 | 1478 | /// |
a1dfa0c6 | 1479 | /// Structs in Rust come in three flavors: Structs with named fields, tuple structs, and unit |
0bf4aa26 XL |
1480 | /// structs. |
1481 | /// | |
1482 | /// ```rust | |
1483 | /// struct Regular { | |
1484 | /// field1: f32, | |
b7449926 | 1485 | /// field2: String, |
0bf4aa26 XL |
1486 | /// pub field3: bool |
1487 | /// } | |
1488 | /// | |
1489 | /// struct Tuple(u32, String); | |
1490 | /// | |
1491 | /// struct Unit; | |
1492 | /// ``` | |
1493 | /// | |
1494 | /// Regular structs are the most commonly used. Each field defined within them has a name and a | |
1495 | /// type, and once defined can be accessed using `example_struct.field` syntax. The fields of a | |
1496 | /// struct share its mutability, so `foo.bar = 2;` would only be valid if `foo` was mutable. Adding | |
1497 | /// `pub` to a field makes it visible to code in other modules, as well as allowing it to be | |
1498 | /// directly accessed and modified. | |
1499 | /// | |
1500 | /// Tuple structs are similar to regular structs, but its fields have no names. They are used like | |
9fa01778 | 1501 | /// tuples, with deconstruction possible via `let TupleStruct(x, y) = foo;` syntax. For accessing |
0bf4aa26 XL |
1502 | /// individual variables, the same syntax is used as with regular tuples, namely `foo.0`, `foo.1`, |
1503 | /// etc, starting at zero. | |
1504 | /// | |
1505 | /// Unit structs are most commonly used as marker. They have a size of zero bytes, but unlike empty | |
1506 | /// enums they can be instantiated, making them isomorphic to the unit type `()`. Unit structs are | |
1507 | /// useful when you need to implement a trait on something, but don't need to store any data inside | |
1508 | /// it. | |
1509 | /// | |
1510 | /// # Instantiation | |
1511 | /// | |
1512 | /// Structs can be instantiated in different ways, all of which can be mixed and | |
1513 | /// matched as needed. The most common way to make a new struct is via a constructor method such as | |
1514 | /// `new()`, but when that isn't available (or you're writing the constructor itself), struct | |
1515 | /// literal syntax is used: | |
1516 | /// | |
1517 | /// ```rust | |
1518 | /// # struct Foo { field1: f32, field2: String, etc: bool } | |
1519 | /// let example = Foo { | |
1520 | /// field1: 42.0, | |
1521 | /// field2: "blah".to_string(), | |
1522 | /// etc: true, | |
1523 | /// }; | |
1524 | /// ``` | |
1525 | /// | |
1526 | /// It's only possible to directly instantiate a struct using struct literal syntax when all of its | |
1527 | /// fields are visible to you. | |
1528 | /// | |
1529 | /// There are a handful of shortcuts provided to make writing constructors more convenient, most | |
1530 | /// common of which is the Field Init shorthand. When there is a variable and a field of the same | |
1531 | /// name, the assignment can be simplified from `field: field` into simply `field`. The following | |
1532 | /// example of a hypothetical constructor demonstrates this: | |
1533 | /// | |
1534 | /// ```rust | |
1535 | /// struct User { | |
1536 | /// name: String, | |
1537 | /// admin: bool, | |
1538 | /// } | |
1539 | /// | |
1540 | /// impl User { | |
1541 | /// pub fn new(name: String) -> Self { | |
1542 | /// Self { | |
1543 | /// name, | |
1544 | /// admin: false, | |
1545 | /// } | |
1546 | /// } | |
b7449926 XL |
1547 | /// } |
1548 | /// ``` | |
1549 | /// | |
0bf4aa26 XL |
1550 | /// Another shortcut for struct instantiation is available, used when you need to make a new |
1551 | /// struct that has the same values as most of a previous struct of the same type, called struct | |
1552 | /// update syntax: | |
1553 | /// | |
1554 | /// ```rust | |
1555 | /// # struct Foo { field1: String, field2: () } | |
1556 | /// # let thing = Foo { field1: "".to_string(), field2: () }; | |
1557 | /// let updated_thing = Foo { | |
1558 | /// field1: "a new value".to_string(), | |
1559 | /// ..thing | |
1560 | /// }; | |
1561 | /// ``` | |
1562 | /// | |
1563 | /// Tuple structs are instantiated in the same way as tuples themselves, except with the struct's | |
1564 | /// name as a prefix: `Foo(123, false, 0.1)`. | |
1565 | /// | |
1566 | /// Empty structs are instantiated with just their name, and don't need anything else. `let thing = | |
1567 | /// EmptyStruct;` | |
1568 | /// | |
1569 | /// # Style conventions | |
1570 | /// | |
9ffffee4 | 1571 | /// Structs are always written in UpperCamelCase, with few exceptions. While the trailing comma on a |
0bf4aa26 XL |
1572 | /// struct's list of fields can be omitted, it's usually kept for convenience in adding and |
1573 | /// removing fields down the line. | |
1574 | /// | |
1575 | /// For more information on structs, take a look at the [Rust Book][book] or the | |
1576 | /// [Reference][reference]. | |
b7449926 | 1577 | /// |
3dfed10e | 1578 | /// [`PhantomData`]: marker::PhantomData |
48663c56 XL |
1579 | /// [book]: ../book/ch05-01-defining-structs.html |
1580 | /// [reference]: ../reference/items/structs.html | |
dfeec247 | 1581 | mod struct_keyword {} |
48663c56 XL |
1582 | |
1583 | #[doc(keyword = "super")] | |
1584 | // | |
1585 | /// The parent of the current [module]. | |
1586 | /// | |
f035d41b XL |
1587 | /// ```rust |
1588 | /// # #![allow(dead_code)] | |
1589 | /// # fn main() {} | |
1590 | /// mod a { | |
1591 | /// pub fn foo() {} | |
1592 | /// } | |
1593 | /// mod b { | |
1594 | /// pub fn foo() { | |
1595 | /// super::a::foo(); // call a's foo function | |
1596 | /// } | |
1597 | /// } | |
1598 | /// ``` | |
1599 | /// | |
1600 | /// It is also possible to use `super` multiple times: `super::super::foo`, | |
1601 | /// going up the ancestor chain. | |
1602 | /// | |
1603 | /// See the [Reference] for more information. | |
48663c56 XL |
1604 | /// |
1605 | /// [module]: ../reference/items/modules.html | |
f035d41b | 1606 | /// [Reference]: ../reference/paths.html#super |
dfeec247 | 1607 | mod super_keyword {} |
48663c56 XL |
1608 | |
1609 | #[doc(keyword = "trait")] | |
1610 | // | |
3dfed10e XL |
1611 | /// A common interface for a group of types. |
1612 | /// | |
1613 | /// A `trait` is like an interface that data types can implement. When a type | |
1614 | /// implements a trait it can be treated abstractly as that trait using generics | |
1615 | /// or trait objects. | |
1616 | /// | |
1617 | /// Traits can be made up of three varieties of associated items: | |
1618 | /// | |
1619 | /// - functions and methods | |
1620 | /// - types | |
1621 | /// - constants | |
1622 | /// | |
1623 | /// Traits may also contain additional type parameters. Those type parameters | |
1624 | /// or the trait itself can be constrained by other traits. | |
1625 | /// | |
1626 | /// Traits can serve as markers or carry other logical semantics that | |
1627 | /// aren't expressed through their items. When a type implements that | |
1628 | /// trait it is promising to uphold its contract. [`Send`] and [`Sync`] are two | |
1629 | /// such marker traits present in the standard library. | |
1630 | /// | |
1631 | /// See the [Reference][Ref-Traits] for a lot more information on traits. | |
1632 | /// | |
1633 | /// # Examples | |
1634 | /// | |
1635 | /// Traits are declared using the `trait` keyword. Types can implement them | |
1636 | /// using [`impl`] `Trait` [`for`] `Type`: | |
1637 | /// | |
1638 | /// ```rust | |
1639 | /// trait Zero { | |
1640 | /// const ZERO: Self; | |
1641 | /// fn is_zero(&self) -> bool; | |
1642 | /// } | |
1643 | /// | |
1644 | /// impl Zero for i32 { | |
1645 | /// const ZERO: Self = 0; | |
1646 | /// | |
1647 | /// fn is_zero(&self) -> bool { | |
1648 | /// *self == Self::ZERO | |
1649 | /// } | |
1650 | /// } | |
1651 | /// | |
1652 | /// assert_eq!(i32::ZERO, 0); | |
1653 | /// assert!(i32::ZERO.is_zero()); | |
1654 | /// assert!(!4.is_zero()); | |
1655 | /// ``` | |
1656 | /// | |
1657 | /// With an associated type: | |
1658 | /// | |
1659 | /// ```rust | |
1660 | /// trait Builder { | |
1661 | /// type Built; | |
1662 | /// | |
1663 | /// fn build(&self) -> Self::Built; | |
1664 | /// } | |
1665 | /// ``` | |
1666 | /// | |
1667 | /// Traits can be generic, with constraints or without: | |
1668 | /// | |
1669 | /// ```rust | |
1670 | /// trait MaybeFrom<T> { | |
1671 | /// fn maybe_from(value: T) -> Option<Self> | |
1672 | /// where | |
1673 | /// Self: Sized; | |
1674 | /// } | |
1675 | /// ``` | |
1676 | /// | |
1677 | /// Traits can build upon the requirements of other traits. In the example | |
1678 | /// below `Iterator` is a **supertrait** and `ThreeIterator` is a **subtrait**: | |
1679 | /// | |
1680 | /// ```rust | |
353b0b11 | 1681 | /// trait ThreeIterator: Iterator { |
3dfed10e XL |
1682 | /// fn next_three(&mut self) -> Option<[Self::Item; 3]>; |
1683 | /// } | |
1684 | /// ``` | |
1685 | /// | |
1686 | /// Traits can be used in functions, as parameters: | |
1687 | /// | |
1688 | /// ```rust | |
1689 | /// # #![allow(dead_code)] | |
1690 | /// fn debug_iter<I: Iterator>(it: I) where I::Item: std::fmt::Debug { | |
1691 | /// for elem in it { | |
5e7ed085 | 1692 | /// println!("{elem:#?}"); |
3dfed10e XL |
1693 | /// } |
1694 | /// } | |
1695 | /// | |
1696 | /// // u8_len_1, u8_len_2 and u8_len_3 are equivalent | |
1697 | /// | |
1698 | /// fn u8_len_1(val: impl Into<Vec<u8>>) -> usize { | |
1699 | /// val.into().len() | |
1700 | /// } | |
1701 | /// | |
1702 | /// fn u8_len_2<T: Into<Vec<u8>>>(val: T) -> usize { | |
1703 | /// val.into().len() | |
1704 | /// } | |
1705 | /// | |
1706 | /// fn u8_len_3<T>(val: T) -> usize | |
1707 | /// where | |
1708 | /// T: Into<Vec<u8>>, | |
1709 | /// { | |
1710 | /// val.into().len() | |
1711 | /// } | |
1712 | /// ``` | |
1713 | /// | |
1714 | /// Or as return types: | |
1715 | /// | |
1716 | /// ```rust | |
1717 | /// # #![allow(dead_code)] | |
1718 | /// fn from_zero_to(v: u8) -> impl Iterator<Item = u8> { | |
1719 | /// (0..v).into_iter() | |
1720 | /// } | |
1721 | /// ``` | |
1722 | /// | |
1723 | /// The use of the [`impl`] keyword in this position allows the function writer | |
1724 | /// to hide the concrete type as an implementation detail which can change | |
1725 | /// without breaking user's code. | |
1726 | /// | |
1727 | /// # Trait objects | |
1728 | /// | |
1729 | /// A *trait object* is an opaque value of another type that implements a set of | |
1730 | /// traits. A trait object implements all specified traits as well as their | |
1731 | /// supertraits (if any). | |
1732 | /// | |
1733 | /// The syntax is the following: `dyn BaseTrait + AutoTrait1 + ... AutoTraitN`. | |
1734 | /// Only one `BaseTrait` can be used so this will not compile: | |
1735 | /// | |
1736 | /// ```rust,compile_fail,E0225 | |
1737 | /// trait A {} | |
1738 | /// trait B {} | |
1739 | /// | |
1740 | /// let _: Box<dyn A + B>; | |
1741 | /// ``` | |
1742 | /// | |
1743 | /// Neither will this, which is a syntax error: | |
1744 | /// | |
1745 | /// ```rust,compile_fail | |
1746 | /// trait A {} | |
1747 | /// trait B {} | |
1748 | /// | |
1749 | /// let _: Box<dyn A + dyn B>; | |
1750 | /// ``` | |
1751 | /// | |
1752 | /// On the other hand, this is correct: | |
1753 | /// | |
1754 | /// ```rust | |
1755 | /// trait A {} | |
1756 | /// | |
1757 | /// let _: Box<dyn A + Send + Sync>; | |
1758 | /// ``` | |
1759 | /// | |
1760 | /// The [Reference][Ref-Trait-Objects] has more information about trait objects, | |
1761 | /// their limitations and the differences between editions. | |
1762 | /// | |
1763 | /// # Unsafe traits | |
48663c56 | 1764 | /// |
3dfed10e XL |
1765 | /// Some traits may be unsafe to implement. Using the [`unsafe`] keyword in |
1766 | /// front of the trait's declaration is used to mark this: | |
48663c56 | 1767 | /// |
3dfed10e XL |
1768 | /// ```rust |
1769 | /// unsafe trait UnsafeTrait {} | |
1770 | /// | |
1771 | /// unsafe impl UnsafeTrait for i32 {} | |
1772 | /// ``` | |
1773 | /// | |
1774 | /// # Differences between the 2015 and 2018 editions | |
1775 | /// | |
fc512014 | 1776 | /// In the 2015 edition the parameters pattern was not needed for traits: |
3dfed10e XL |
1777 | /// |
1778 | /// ```rust,edition2015 | |
cdc7bbd5 | 1779 | /// # #![allow(anonymous_parameters)] |
3dfed10e XL |
1780 | /// trait Tr { |
1781 | /// fn f(i32); | |
1782 | /// } | |
1783 | /// ``` | |
1784 | /// | |
1785 | /// This behavior is no longer valid in edition 2018. | |
1786 | /// | |
1787 | /// [`for`]: keyword.for.html | |
1788 | /// [`impl`]: keyword.impl.html | |
1789 | /// [`unsafe`]: keyword.unsafe.html | |
1790 | /// [Ref-Traits]: ../reference/items/traits.html | |
1791 | /// [Ref-Trait-Objects]: ../reference/types/trait-object.html | |
dfeec247 | 1792 | mod trait_keyword {} |
48663c56 XL |
1793 | |
1794 | #[doc(keyword = "true")] | |
1795 | // | |
1796 | /// A value of type [`bool`] representing logical **true**. | |
1797 | /// | |
74b04a01 XL |
1798 | /// Logically `true` is not equal to [`false`]. |
1799 | /// | |
1800 | /// ## Control structures that check for **true** | |
1801 | /// | |
1802 | /// Several of Rust's control structures will check for a `bool` condition evaluating to **true**. | |
1803 | /// | |
1804 | /// * The condition in an [`if`] expression must be of type `bool`. | |
1805 | /// Whenever that condition evaluates to **true**, the `if` expression takes | |
1806 | /// on the value of the first block. If however, the condition evaluates | |
1807 | /// to `false`, the expression takes on value of the `else` block if there is one. | |
1808 | /// | |
1809 | /// * [`while`] is another control flow construct expecting a `bool`-typed condition. | |
1810 | /// As long as the condition evaluates to **true**, the `while` loop will continually | |
1811 | /// evaluate its associated block. | |
48663c56 | 1812 | /// |
74b04a01 XL |
1813 | /// * [`match`] arms can have guard clauses on them. |
1814 | /// | |
1815 | /// [`if`]: keyword.if.html | |
1816 | /// [`while`]: keyword.while.html | |
1817 | /// [`match`]: ../reference/expressions/match-expr.html#match-guards | |
1818 | /// [`false`]: keyword.false.html | |
dfeec247 | 1819 | mod true_keyword {} |
48663c56 XL |
1820 | |
1821 | #[doc(keyword = "type")] | |
1822 | // | |
1823 | /// Define an alias for an existing type. | |
1824 | /// | |
f035d41b | 1825 | /// The syntax is `type Name = ExistingType;`. |
48663c56 | 1826 | /// |
f035d41b XL |
1827 | /// # Examples |
1828 | /// | |
1829 | /// `type` does **not** create a new type: | |
1830 | /// | |
1831 | /// ```rust | |
1832 | /// type Meters = u32; | |
1833 | /// type Kilograms = u32; | |
1834 | /// | |
1835 | /// let m: Meters = 3; | |
1836 | /// let k: Kilograms = 3; | |
1837 | /// | |
1838 | /// assert_eq!(m, k); | |
1839 | /// ``` | |
1840 | /// | |
1841 | /// In traits, `type` is used to declare an [associated type]: | |
1842 | /// | |
1843 | /// ```rust | |
1844 | /// trait Iterator { | |
1845 | /// // associated type declaration | |
1846 | /// type Item; | |
1847 | /// fn next(&mut self) -> Option<Self::Item>; | |
1848 | /// } | |
1849 | /// | |
1850 | /// struct Once<T>(Option<T>); | |
1851 | /// | |
1852 | /// impl<T> Iterator for Once<T> { | |
1853 | /// // associated type definition | |
1854 | /// type Item = T; | |
1855 | /// fn next(&mut self) -> Option<Self::Item> { | |
1856 | /// self.0.take() | |
1857 | /// } | |
1858 | /// } | |
1859 | /// ``` | |
1860 | /// | |
1861 | /// [`trait`]: keyword.trait.html | |
1862 | /// [associated type]: ../reference/items/associated-items.html#associated-types | |
dfeec247 | 1863 | mod type_keyword {} |
48663c56 XL |
1864 | |
1865 | #[doc(keyword = "unsafe")] | |
1866 | // | |
3dfed10e XL |
1867 | /// Code or interfaces whose [memory safety] cannot be verified by the type |
1868 | /// system. | |
1869 | /// | |
2b03887a FG |
1870 | /// The `unsafe` keyword has two uses: |
1871 | /// - to declare the existence of contracts the compiler can't check (`unsafe fn` and `unsafe | |
1872 | /// trait`), | |
1873 | /// - and to declare that a programmer has checked that these contracts have been upheld (`unsafe | |
1874 | /// {}` and `unsafe impl`, but also `unsafe fn` -- see below). | |
1875 | /// | |
1876 | /// They are not mutually exclusive, as can be seen in `unsafe fn`: the body of an `unsafe fn` is, | |
1877 | /// by default, treated like an unsafe block. The `unsafe_op_in_unsafe_fn` lint can be enabled to | |
1878 | /// change that. | |
3dfed10e XL |
1879 | /// |
1880 | /// # Unsafe abilities | |
1881 | /// | |
1882 | /// **No matter what, Safe Rust can't cause Undefined Behavior**. This is | |
1883 | /// referred to as [soundness]: a well-typed program actually has the desired | |
1884 | /// properties. The [Nomicon][nomicon-soundness] has a more detailed explanation | |
1885 | /// on the subject. | |
1886 | /// | |
1887 | /// To ensure soundness, Safe Rust is restricted enough that it can be | |
1888 | /// automatically checked. Sometimes, however, it is necessary to write code | |
1889 | /// that is correct for reasons which are too clever for the compiler to | |
1890 | /// understand. In those cases, you need to use Unsafe Rust. | |
1891 | /// | |
1892 | /// Here are the abilities Unsafe Rust has in addition to Safe Rust: | |
1893 | /// | |
1894 | /// - Dereference [raw pointers] | |
1895 | /// - Implement `unsafe` [`trait`]s | |
1896 | /// - Call `unsafe` functions | |
1897 | /// - Mutate [`static`]s (including [`extern`]al ones) | |
1898 | /// - Access fields of [`union`]s | |
1899 | /// | |
1900 | /// However, this extra power comes with extra responsibilities: it is now up to | |
1901 | /// you to ensure soundness. The `unsafe` keyword helps by clearly marking the | |
1902 | /// pieces of code that need to worry about this. | |
1903 | /// | |
1904 | /// ## The different meanings of `unsafe` | |
1905 | /// | |
1906 | /// Not all uses of `unsafe` are equivalent: some are here to mark the existence | |
1907 | /// of a contract the programmer must check, others are to say "I have checked | |
1908 | /// the contract, go ahead and do this". The following | |
1909 | /// [discussion on Rust Internals] has more in-depth explanations about this but | |
1910 | /// here is a summary of the main points: | |
1911 | /// | |
1912 | /// - `unsafe fn`: calling this function means abiding by a contract the | |
1913 | /// compiler cannot enforce. | |
1914 | /// - `unsafe trait`: implementing the [`trait`] means abiding by a | |
1915 | /// contract the compiler cannot enforce. | |
1916 | /// - `unsafe {}`: the contract necessary to call the operations inside the | |
1917 | /// block has been checked by the programmer and is guaranteed to be respected. | |
1918 | /// - `unsafe impl`: the contract necessary to implement the trait has been | |
1919 | /// checked by the programmer and is guaranteed to be respected. | |
1920 | /// | |
2b03887a | 1921 | /// By default, `unsafe fn` also acts like an `unsafe {}` block |
3dfed10e XL |
1922 | /// around the code inside the function. This means it is not just a signal to |
1923 | /// the caller, but also promises that the preconditions for the operations | |
2b03887a FG |
1924 | /// inside the function are upheld. Mixing these two meanings can be confusing, so the |
1925 | /// `unsafe_op_in_unsafe_fn` lint can be enabled to warn against that and require explicit unsafe | |
1926 | /// blocks even inside `unsafe fn`. | |
3dfed10e | 1927 | /// |
49aad941 | 1928 | /// See the [Rustonomicon] and the [Reference] for more information. |
3dfed10e XL |
1929 | /// |
1930 | /// # Examples | |
1931 | /// | |
1932 | /// ## Marking elements as `unsafe` | |
1933 | /// | |
1934 | /// `unsafe` can be used on functions. Note that functions and statics declared | |
1935 | /// in [`extern`] blocks are implicitly marked as `unsafe` (but not functions | |
1936 | /// declared as `extern "something" fn ...`). Mutable statics are always unsafe, | |
1937 | /// wherever they are declared. Methods can also be declared as `unsafe`: | |
1938 | /// | |
1939 | /// ```rust | |
1940 | /// # #![allow(dead_code)] | |
1941 | /// static mut FOO: &str = "hello"; | |
1942 | /// | |
1943 | /// unsafe fn unsafe_fn() {} | |
1944 | /// | |
1945 | /// extern "C" { | |
1946 | /// fn unsafe_extern_fn(); | |
1947 | /// static BAR: *mut u32; | |
1948 | /// } | |
1949 | /// | |
1950 | /// trait SafeTraitWithUnsafeMethod { | |
1951 | /// unsafe fn unsafe_method(&self); | |
1952 | /// } | |
1953 | /// | |
1954 | /// struct S; | |
1955 | /// | |
1956 | /// impl S { | |
1957 | /// unsafe fn unsafe_method_on_struct() {} | |
1958 | /// } | |
1959 | /// ``` | |
1960 | /// | |
1961 | /// Traits can also be declared as `unsafe`: | |
1962 | /// | |
1963 | /// ```rust | |
1964 | /// unsafe trait UnsafeTrait {} | |
1965 | /// ``` | |
1966 | /// | |
1967 | /// Since `unsafe fn` and `unsafe trait` indicate that there is a safety | |
1968 | /// contract that the compiler cannot enforce, documenting it is important. The | |
1969 | /// standard library has many examples of this, like the following which is an | |
1970 | /// extract from [`Vec::set_len`]. The `# Safety` section explains the contract | |
1971 | /// that must be fulfilled to safely call the function. | |
1972 | /// | |
1973 | /// ```rust,ignore (stub-to-show-doc-example) | |
1974 | /// /// Forces the length of the vector to `new_len`. | |
1975 | /// /// | |
1976 | /// /// This is a low-level operation that maintains none of the normal | |
1977 | /// /// invariants of the type. Normally changing the length of a vector | |
1978 | /// /// is done using one of the safe operations instead, such as | |
1979 | /// /// `truncate`, `resize`, `extend`, or `clear`. | |
1980 | /// /// | |
1981 | /// /// # Safety | |
1982 | /// /// | |
1983 | /// /// - `new_len` must be less than or equal to `capacity()`. | |
1984 | /// /// - The elements at `old_len..new_len` must be initialized. | |
1985 | /// pub unsafe fn set_len(&mut self, new_len: usize) | |
1986 | /// ``` | |
1987 | /// | |
1988 | /// ## Using `unsafe {}` blocks and `impl`s | |
1989 | /// | |
1990 | /// Performing `unsafe` operations requires an `unsafe {}` block: | |
1991 | /// | |
1992 | /// ```rust | |
1993 | /// # #![allow(dead_code)] | |
2b03887a FG |
1994 | /// #![deny(unsafe_op_in_unsafe_fn)] |
1995 | /// | |
3dfed10e XL |
1996 | /// /// Dereference the given pointer. |
1997 | /// /// | |
1998 | /// /// # Safety | |
1999 | /// /// | |
2000 | /// /// `ptr` must be aligned and must not be dangling. | |
2001 | /// unsafe fn deref_unchecked(ptr: *const i32) -> i32 { | |
2b03887a FG |
2002 | /// // SAFETY: the caller is required to ensure that `ptr` is aligned and dereferenceable. |
2003 | /// unsafe { *ptr } | |
3dfed10e XL |
2004 | /// } |
2005 | /// | |
2006 | /// let a = 3; | |
2007 | /// let b = &a as *const _; | |
2008 | /// // SAFETY: `a` has not been dropped and references are always aligned, | |
2009 | /// // so `b` is a valid address. | |
2010 | /// unsafe { assert_eq!(*b, deref_unchecked(b)); }; | |
2011 | /// ``` | |
2012 | /// | |
2b03887a FG |
2013 | /// ## `unsafe` and traits |
2014 | /// | |
2015 | /// The interactions of `unsafe` and traits can be surprising, so let us contrast the | |
2016 | /// two combinations of safe `fn` in `unsafe trait` and `unsafe fn` in safe trait using two | |
2017 | /// examples: | |
2018 | /// | |
2019 | /// ```rust | |
2020 | /// /// # Safety | |
2021 | /// /// | |
2022 | /// /// `make_even` must return an even number. | |
2023 | /// unsafe trait MakeEven { | |
2024 | /// fn make_even(&self) -> i32; | |
2025 | /// } | |
2026 | /// | |
2027 | /// // SAFETY: Our `make_even` always returns something even. | |
2028 | /// unsafe impl MakeEven for i32 { | |
2029 | /// fn make_even(&self) -> i32 { | |
2030 | /// self << 1 | |
2031 | /// } | |
2032 | /// } | |
2033 | /// | |
2034 | /// fn use_make_even(x: impl MakeEven) { | |
2035 | /// if x.make_even() % 2 == 1 { | |
2036 | /// // SAFETY: this can never happen, because all `MakeEven` implementations | |
2037 | /// // ensure that `make_even` returns something even. | |
2038 | /// unsafe { std::hint::unreachable_unchecked() }; | |
2039 | /// } | |
2040 | /// } | |
2041 | /// ``` | |
2042 | /// | |
2043 | /// Note how the safety contract of the trait is upheld by the implementation, and is itself used to | |
2044 | /// uphold the safety contract of the unsafe function `unreachable_unchecked` called by | |
2045 | /// `use_make_even`. `make_even` itself is a safe function because its *callers* do not have to | |
2046 | /// worry about any contract, only the *implementation* of `MakeEven` is required to uphold a | |
2047 | /// certain contract. `use_make_even` is safe because it can use the promise made by `MakeEven` | |
2048 | /// implementations to uphold the safety contract of the `unsafe fn unreachable_unchecked` it calls. | |
2049 | /// | |
2050 | /// It is also possible to have `unsafe fn` in a regular safe `trait`: | |
3dfed10e XL |
2051 | /// |
2052 | /// ```rust | |
2b03887a FG |
2053 | /// # #![feature(never_type)] |
2054 | /// #![deny(unsafe_op_in_unsafe_fn)] | |
2055 | /// | |
2056 | /// trait Indexable { | |
2057 | /// const LEN: usize; | |
2058 | /// | |
2059 | /// /// # Safety | |
2060 | /// /// | |
2061 | /// /// The caller must ensure that `idx < LEN`. | |
2062 | /// unsafe fn idx_unchecked(&self, idx: usize) -> i32; | |
2063 | /// } | |
2064 | /// | |
2065 | /// // The implementation for `i32` doesn't need to do any contract reasoning. | |
2066 | /// impl Indexable for i32 { | |
2067 | /// const LEN: usize = 1; | |
2068 | /// | |
2069 | /// unsafe fn idx_unchecked(&self, idx: usize) -> i32 { | |
2070 | /// debug_assert_eq!(idx, 0); | |
2071 | /// *self | |
2072 | /// } | |
2073 | /// } | |
2074 | /// | |
2075 | /// // The implementation for arrays exploits the function contract to | |
2076 | /// // make use of `get_unchecked` on slices and avoid a run-time check. | |
2077 | /// impl Indexable for [i32; 42] { | |
2078 | /// const LEN: usize = 42; | |
2079 | /// | |
2080 | /// unsafe fn idx_unchecked(&self, idx: usize) -> i32 { | |
2081 | /// // SAFETY: As per this trait's documentation, the caller ensures | |
2082 | /// // that `idx < 42`. | |
2083 | /// unsafe { *self.get_unchecked(idx) } | |
3dfed10e XL |
2084 | /// } |
2085 | /// } | |
48663c56 | 2086 | /// |
2b03887a FG |
2087 | /// // The implementation for the never type declares a length of 0, |
2088 | /// // which means `idx_unchecked` can never be called. | |
2089 | /// impl Indexable for ! { | |
2090 | /// const LEN: usize = 0; | |
2091 | /// | |
2092 | /// unsafe fn idx_unchecked(&self, idx: usize) -> i32 { | |
2093 | /// // SAFETY: As per this trait's documentation, the caller ensures | |
2094 | /// // that `idx < 0`, which is impossible, so this is dead code. | |
2095 | /// unsafe { std::hint::unreachable_unchecked() } | |
2096 | /// } | |
2097 | /// } | |
2098 | /// | |
2099 | /// fn use_indexable<I: Indexable>(x: I, idx: usize) -> i32 { | |
2100 | /// if idx < I::LEN { | |
2101 | /// // SAFETY: We have checked that `idx < I::LEN`. | |
2102 | /// unsafe { x.idx_unchecked(idx) } | |
2103 | /// } else { | |
2104 | /// panic!("index out-of-bounds") | |
2105 | /// } | |
2106 | /// } | |
3dfed10e | 2107 | /// ``` |
48663c56 | 2108 | /// |
2b03887a FG |
2109 | /// This time, `use_indexable` is safe because it uses a run-time check to discharge the safety |
2110 | /// contract of `idx_unchecked`. Implementing `Indexable` is safe because when writing | |
2111 | /// `idx_unchecked`, we don't have to worry: our *callers* need to discharge a proof obligation | |
2112 | /// (like `use_indexable` does), but the *implementation* of `get_unchecked` has no proof obligation | |
2113 | /// to contend with. Of course, the implementation of `Indexable` may choose to call other unsafe | |
2114 | /// operations, and then it needs an `unsafe` *block* to indicate it discharged the proof | |
2115 | /// obligations of its callees. (We enabled `unsafe_op_in_unsafe_fn`, so the body of `idx_unchecked` | |
2116 | /// is not implicitly an unsafe block.) For that purpose it can make use of the contract that all | |
2117 | /// its callers must uphold -- the fact that `idx < LEN`. | |
2118 | /// | |
2119 | /// Formally speaking, an `unsafe fn` in a trait is a function with *preconditions* that go beyond | |
2120 | /// those encoded by the argument types (such as `idx < LEN`), whereas an `unsafe trait` can declare | |
2121 | /// that some of its functions have *postconditions* that go beyond those encoded in the return type | |
2122 | /// (such as returning an even integer). If a trait needs a function with both extra precondition | |
2123 | /// and extra postcondition, then it needs an `unsafe fn` in an `unsafe trait`. | |
2124 | /// | |
3dfed10e XL |
2125 | /// [`extern`]: keyword.extern.html |
2126 | /// [`trait`]: keyword.trait.html | |
2127 | /// [`static`]: keyword.static.html | |
2128 | /// [`union`]: keyword.union.html | |
2129 | /// [`impl`]: keyword.impl.html | |
2130 | /// [raw pointers]: ../reference/types/pointer.html | |
48663c56 | 2131 | /// [memory safety]: ../book/ch19-01-unsafe-rust.html |
49aad941 | 2132 | /// [Rustonomicon]: ../nomicon/index.html |
3dfed10e XL |
2133 | /// [nomicon-soundness]: ../nomicon/safe-unsafe-meaning.html |
2134 | /// [soundness]: https://rust-lang.github.io/unsafe-code-guidelines/glossary.html#soundness-of-code--of-a-library | |
2135 | /// [Reference]: ../reference/unsafety.html | |
3dfed10e | 2136 | /// [discussion on Rust Internals]: https://internals.rust-lang.org/t/what-does-unsafe-mean/6696 |
dfeec247 | 2137 | mod unsafe_keyword {} |
48663c56 XL |
2138 | |
2139 | #[doc(keyword = "use")] | |
2140 | // | |
2141 | /// Import or rename items from other crates or modules. | |
2142 | /// | |
f035d41b XL |
2143 | /// Usually a `use` keyword is used to shorten the path required to refer to a module item. |
2144 | /// The keyword may appear in modules, blocks and even functions, usually at the top. | |
2145 | /// | |
2146 | /// The most basic usage of the keyword is `use path::to::item;`, | |
2147 | /// though a number of convenient shortcuts are supported: | |
2148 | /// | |
2149 | /// * Simultaneously binding a list of paths with a common prefix, | |
2150 | /// using the glob-like brace syntax `use a::b::{c, d, e::f, g::h::i};` | |
2151 | /// * Simultaneously binding a list of paths with a common prefix and their common parent module, | |
2152 | /// using the [`self`] keyword, such as `use a::b::{self, c, d::e};` | |
2153 | /// * Rebinding the target name as a new local name, using the syntax `use p::q::r as x;`. | |
2154 | /// This can also be used with the last two features: `use a::b::{self as ab, c as abc}`. | |
2155 | /// * Binding all paths matching a given prefix, | |
2156 | /// using the asterisk wildcard syntax `use a::b::*;`. | |
2157 | /// * Nesting groups of the previous features multiple times, | |
2158 | /// such as `use a::b::{self as ab, c, d::{*, e::f}};` | |
2159 | /// * Reexporting with visibility modifiers such as `pub use a::b;` | |
2160 | /// * Importing with `_` to only import the methods of a trait without binding it to a name | |
2161 | /// (to avoid conflict for example): `use ::std::io::Read as _;`. | |
2162 | /// | |
2163 | /// Using path qualifiers like [`crate`], [`super`] or [`self`] is supported: `use crate::a::b;`. | |
2164 | /// | |
2165 | /// Note that when the wildcard `*` is used on a type, it does not import its methods (though | |
2166 | /// for `enum`s it imports the variants, as shown in the example below). | |
2167 | /// | |
2168 | /// ```compile_fail,edition2018 | |
2169 | /// enum ExampleEnum { | |
2170 | /// VariantA, | |
2171 | /// VariantB, | |
2172 | /// } | |
48663c56 | 2173 | /// |
f035d41b XL |
2174 | /// impl ExampleEnum { |
2175 | /// fn new() -> Self { | |
2176 | /// Self::VariantA | |
2177 | /// } | |
2178 | /// } | |
2179 | /// | |
2180 | /// use ExampleEnum::*; | |
2181 | /// | |
2182 | /// // Compiles. | |
2183 | /// let _ = VariantA; | |
2184 | /// | |
2185 | /// // Does not compile ! | |
2186 | /// let n = new(); | |
2187 | /// ``` | |
2188 | /// | |
2189 | /// For more information on `use` and paths in general, see the [Reference]. | |
2190 | /// | |
2191 | /// The differences about paths and the `use` keyword between the 2015 and 2018 editions | |
2192 | /// can also be found in the [Reference]. | |
2193 | /// | |
2194 | /// [`crate`]: keyword.crate.html | |
2195 | /// [`self`]: keyword.self.html | |
2196 | /// [`super`]: keyword.super.html | |
2197 | /// [Reference]: ../reference/items/use-declarations.html | |
dfeec247 | 2198 | mod use_keyword {} |
48663c56 XL |
2199 | |
2200 | #[doc(keyword = "where")] | |
2201 | // | |
2202 | /// Add constraints that must be upheld to use an item. | |
2203 | /// | |
3dfed10e | 2204 | /// `where` allows specifying constraints on lifetime and generic parameters. |
f2b60f7d | 2205 | /// The [RFC] introducing `where` contains detailed information about the |
3dfed10e XL |
2206 | /// keyword. |
2207 | /// | |
2208 | /// # Examples | |
2209 | /// | |
2210 | /// `where` can be used for constraints with traits: | |
2211 | /// | |
2212 | /// ```rust | |
2213 | /// fn new<T: Default>() -> T { | |
2214 | /// T::default() | |
2215 | /// } | |
2216 | /// | |
2217 | /// fn new_where<T>() -> T | |
2218 | /// where | |
2219 | /// T: Default, | |
2220 | /// { | |
2221 | /// T::default() | |
2222 | /// } | |
2223 | /// | |
2224 | /// assert_eq!(0.0, new()); | |
2225 | /// assert_eq!(0.0, new_where()); | |
2226 | /// | |
2227 | /// assert_eq!(0, new()); | |
2228 | /// assert_eq!(0, new_where()); | |
2229 | /// ``` | |
2230 | /// | |
2231 | /// `where` can also be used for lifetimes. | |
2232 | /// | |
2233 | /// This compiles because `longer` outlives `shorter`, thus the constraint is | |
2234 | /// respected: | |
2235 | /// | |
2236 | /// ```rust | |
2237 | /// fn select<'short, 'long>(s1: &'short str, s2: &'long str, second: bool) -> &'short str | |
2238 | /// where | |
2239 | /// 'long: 'short, | |
2240 | /// { | |
2241 | /// if second { s2 } else { s1 } | |
2242 | /// } | |
2243 | /// | |
2244 | /// let outer = String::from("Long living ref"); | |
2245 | /// let longer = &outer; | |
2246 | /// { | |
2247 | /// let inner = String::from("Short living ref"); | |
2248 | /// let shorter = &inner; | |
2249 | /// | |
2250 | /// assert_eq!(select(shorter, longer, false), shorter); | |
2251 | /// assert_eq!(select(shorter, longer, true), longer); | |
2252 | /// } | |
2253 | /// ``` | |
2254 | /// | |
2255 | /// On the other hand, this will not compile because the `where 'b: 'a` clause | |
2256 | /// is missing: the `'b` lifetime is not known to live at least as long as `'a` | |
2257 | /// which means this function cannot ensure it always returns a valid reference: | |
2258 | /// | |
923072b8 | 2259 | /// ```rust,compile_fail |
3dfed10e XL |
2260 | /// fn select<'a, 'b>(s1: &'a str, s2: &'b str, second: bool) -> &'a str |
2261 | /// { | |
2262 | /// if second { s2 } else { s1 } | |
2263 | /// } | |
2264 | /// ``` | |
2265 | /// | |
2266 | /// `where` can also be used to express more complicated constraints that cannot | |
2267 | /// be written with the `<T: Trait>` syntax: | |
2268 | /// | |
2269 | /// ```rust | |
2270 | /// fn first_or_default<I>(mut i: I) -> I::Item | |
2271 | /// where | |
2272 | /// I: Iterator, | |
2273 | /// I::Item: Default, | |
2274 | /// { | |
2275 | /// i.next().unwrap_or_else(I::Item::default) | |
2276 | /// } | |
2277 | /// | |
5099ac24 | 2278 | /// assert_eq!(first_or_default([1, 2, 3].into_iter()), 1); |
3dfed10e XL |
2279 | /// assert_eq!(first_or_default(Vec::<i32>::new().into_iter()), 0); |
2280 | /// ``` | |
2281 | /// | |
2282 | /// `where` is available anywhere generic and lifetime parameters are available, | |
2283 | /// as can be seen with the [`Cow`](crate::borrow::Cow) type from the standard | |
2284 | /// library: | |
2285 | /// | |
2286 | /// ```rust | |
2287 | /// # #![allow(dead_code)] | |
2288 | /// pub enum Cow<'a, B> | |
2289 | /// where | |
49aad941 | 2290 | /// B: ToOwned + ?Sized, |
923072b8 | 2291 | /// { |
3dfed10e XL |
2292 | /// Borrowed(&'a B), |
2293 | /// Owned(<B as ToOwned>::Owned), | |
2294 | /// } | |
2295 | /// ``` | |
48663c56 | 2296 | /// |
3dfed10e | 2297 | /// [RFC]: https://github.com/rust-lang/rfcs/blob/master/text/0135-where.md |
dfeec247 | 2298 | mod where_keyword {} |
48663c56 | 2299 | |
48663c56 XL |
2300 | // 2018 Edition keywords |
2301 | ||
fc512014 | 2302 | #[doc(alias = "promise")] |
48663c56 XL |
2303 | #[doc(keyword = "async")] |
2304 | // | |
2305 | /// Return a [`Future`] instead of blocking the current thread. | |
2306 | /// | |
dfeec247 XL |
2307 | /// Use `async` in front of `fn`, `closure`, or a `block` to turn the marked code into a `Future`. |
2308 | /// As such the code will not be run immediately, but will only be evaluated when the returned | |
5e7ed085 | 2309 | /// future is [`.await`]ed. |
dfeec247 | 2310 | /// |
5e7ed085 | 2311 | /// We have written an [async book] detailing `async`/`await` and trade-offs compared to using threads. |
dfeec247 XL |
2312 | /// |
2313 | /// ## Editions | |
2314 | /// | |
2315 | /// `async` is a keyword from the 2018 edition onwards. | |
2316 | /// | |
5e7ed085 | 2317 | /// It is available for use in stable Rust from version 1.39 onwards. |
48663c56 | 2318 | /// |
3dfed10e | 2319 | /// [`Future`]: future::Future |
5e7ed085 | 2320 | /// [`.await`]: ../std/keyword.await.html |
dfeec247 XL |
2321 | /// [async book]: https://rust-lang.github.io/async-book/ |
2322 | mod async_keyword {} | |
48663c56 | 2323 | |
48663c56 XL |
2324 | #[doc(keyword = "await")] |
2325 | // | |
2326 | /// Suspend execution until the result of a [`Future`] is ready. | |
2327 | /// | |
5e7ed085 | 2328 | /// `.await`ing a future will suspend the current function's execution until the executor |
dfeec247 XL |
2329 | /// has run the future to completion. |
2330 | /// | |
5e7ed085 | 2331 | /// Read the [async book] for details on how [`async`]/`await` and executors work. |
dfeec247 XL |
2332 | /// |
2333 | /// ## Editions | |
2334 | /// | |
2335 | /// `await` is a keyword from the 2018 edition onwards. | |
2336 | /// | |
5e7ed085 | 2337 | /// It is available for use in stable Rust from version 1.39 onwards. |
48663c56 | 2338 | /// |
3dfed10e | 2339 | /// [`Future`]: future::Future |
dfeec247 | 2340 | /// [async book]: https://rust-lang.github.io/async-book/ |
5e7ed085 | 2341 | /// [`async`]: ../std/keyword.async.html |
dfeec247 | 2342 | mod await_keyword {} |
48663c56 XL |
2343 | |
2344 | #[doc(keyword = "dyn")] | |
2345 | // | |
74b04a01 | 2346 | /// `dyn` is a prefix of a [trait object]'s type. |
48663c56 | 2347 | /// |
74b04a01 | 2348 | /// The `dyn` keyword is used to highlight that calls to methods on the associated `Trait` |
923072b8 | 2349 | /// are [dynamically dispatched]. To use the trait this way, it must be 'object safe'. |
74b04a01 XL |
2350 | /// |
2351 | /// Unlike generic parameters or `impl Trait`, the compiler does not know the concrete type that | |
2352 | /// is being passed. That is, the type has been [erased]. | |
2353 | /// As such, a `dyn Trait` reference contains _two_ pointers. | |
2354 | /// One pointer goes to the data (e.g., an instance of a struct). | |
2355 | /// Another pointer goes to a map of method call names to function pointers | |
2356 | /// (known as a virtual method table or vtable). | |
2357 | /// | |
2358 | /// At run-time, when a method needs to be called on the `dyn Trait`, the vtable is consulted to get | |
2359 | /// the function pointer and then that function pointer is called. | |
2360 | /// | |
136023e0 XL |
2361 | /// See the Reference for more information on [trait objects][ref-trait-obj] |
2362 | /// and [object safety][ref-obj-safety]. | |
2363 | /// | |
74b04a01 XL |
2364 | /// ## Trade-offs |
2365 | /// | |
2366 | /// The above indirection is the additional runtime cost of calling a function on a `dyn Trait`. | |
2367 | /// Methods called by dynamic dispatch generally cannot be inlined by the compiler. | |
2368 | /// | |
2369 | /// However, `dyn Trait` is likely to produce smaller code than `impl Trait` / generic parameters as | |
2370 | /// the method won't be duplicated for each concrete type. | |
2371 | /// | |
48663c56 | 2372 | /// [trait object]: ../book/ch17-02-trait-objects.html |
923072b8 | 2373 | /// [dynamically dispatched]: https://en.wikipedia.org/wiki/Dynamic_dispatch |
136023e0 XL |
2374 | /// [ref-trait-obj]: ../reference/types/trait-object.html |
2375 | /// [ref-obj-safety]: ../reference/items/traits.html#object-safety | |
74b04a01 | 2376 | /// [erased]: https://en.wikipedia.org/wiki/Type_erasure |
dfeec247 | 2377 | mod dyn_keyword {} |
48663c56 XL |
2378 | |
2379 | #[doc(keyword = "union")] | |
2380 | // | |
2381 | /// The [Rust equivalent of a C-style union][union]. | |
2382 | /// | |
f035d41b XL |
2383 | /// A `union` looks like a [`struct`] in terms of declaration, but all of its |
2384 | /// fields exist in the same memory, superimposed over one another. For instance, | |
2385 | /// if we wanted some bits in memory that we sometimes interpret as a `u32` and | |
2386 | /// sometimes as an `f32`, we could write: | |
48663c56 | 2387 | /// |
f035d41b XL |
2388 | /// ```rust |
2389 | /// union IntOrFloat { | |
2390 | /// i: u32, | |
2391 | /// f: f32, | |
2392 | /// } | |
2393 | /// | |
2394 | /// let mut u = IntOrFloat { f: 1.0 }; | |
94222f64 | 2395 | /// // Reading the fields of a union is always unsafe |
f035d41b XL |
2396 | /// assert_eq!(unsafe { u.i }, 1065353216); |
2397 | /// // Updating through any of the field will modify all of them | |
2398 | /// u.i = 1073741824; | |
2399 | /// assert_eq!(unsafe { u.f }, 2.0); | |
2400 | /// ``` | |
2401 | /// | |
2402 | /// # Matching on unions | |
2403 | /// | |
2404 | /// It is possible to use pattern matching on `union`s. A single field name must | |
2405 | /// be used and it must match the name of one of the `union`'s field. | |
2406 | /// Like reading from a `union`, pattern matching on a `union` requires `unsafe`. | |
2407 | /// | |
2408 | /// ```rust | |
2409 | /// union IntOrFloat { | |
2410 | /// i: u32, | |
2411 | /// f: f32, | |
2412 | /// } | |
2413 | /// | |
2414 | /// let u = IntOrFloat { f: 1.0 }; | |
2415 | /// | |
2416 | /// unsafe { | |
2417 | /// match u { | |
2418 | /// IntOrFloat { i: 10 } => println!("Found exactly ten!"), | |
2419 | /// // Matching the field `f` provides an `f32`. | |
5e7ed085 | 2420 | /// IntOrFloat { f } => println!("Found f = {f} !"), |
f035d41b XL |
2421 | /// } |
2422 | /// } | |
2423 | /// ``` | |
2424 | /// | |
2425 | /// # References to union fields | |
2426 | /// | |
2427 | /// All fields in a `union` are all at the same place in memory which means | |
2428 | /// borrowing one borrows the entire `union`, for the same lifetime: | |
2429 | /// | |
2430 | /// ```rust,compile_fail,E0502 | |
2431 | /// union IntOrFloat { | |
2432 | /// i: u32, | |
2433 | /// f: f32, | |
2434 | /// } | |
2435 | /// | |
2436 | /// let mut u = IntOrFloat { f: 1.0 }; | |
2437 | /// | |
2438 | /// let f = unsafe { &u.f }; | |
2439 | /// // This will not compile because the field has already been borrowed, even | |
2440 | /// // if only immutably | |
2441 | /// let i = unsafe { &mut u.i }; | |
2442 | /// | |
2443 | /// *i = 10; | |
5e7ed085 | 2444 | /// println!("f = {f} and i = {i}"); |
f035d41b XL |
2445 | /// ``` |
2446 | /// | |
f2b60f7d | 2447 | /// See the [Reference][union] for more information on `union`s. |
f035d41b XL |
2448 | /// |
2449 | /// [`struct`]: keyword.struct.html | |
48663c56 | 2450 | /// [union]: ../reference/items/unions.html |
dfeec247 | 2451 | mod union_keyword {} |