|
1 | 1 | #[doc(keyword = "as")]
|
2 | 2 | //
|
3 |
| -/// Cast between types, or rename an import. |
| 3 | +/// The `as` keyword is used in many syntactic locations: |
| 4 | +/// * `as` is used to [cast between types][Reference], |
| 5 | +/// * `as` is used to rename an import in [`use`] and [`extern crate`][`crate`] statements, |
| 6 | +/// * `as` is also used to [disambiguate trait implementations][Disambiguation] |
4 | 7 | ///
|
5 |
| -/// `as` is most commonly used to turn primitive types into other primitive types, but it has other |
| 8 | +/// In the type-casting sense, `as` is most commonly used to turn primitive types into other primitive types, but it has other |
6 | 9 | /// uses that include turning pointers into addresses, addresses into pointers, and pointers into
|
7 | 10 | /// other pointers.
|
8 | 11 | ///
|
|
14 | 17 | /// assert_eq!(true as u8 + thing2 as u8, 100);
|
15 | 18 | /// ```
|
16 | 19 | ///
|
17 |
| -/// In general, any cast that can be performed via ascribing the type can also be done using `as`, |
| 20 | +/// In general, any type-cast that can be performed via ascribing the type can also be done using `as`, |
18 | 21 | /// so instead of writing `let x: u32 = 123`, you can write `let x = 123 as u32` (note: `let x: u32
|
19 | 22 | /// = 123` would be best in that situation). The same is not true in the other direction, however;
|
20 | 23 | /// explicitly using `as` allows a few more coercions that aren't allowed implicitly, such as
|
|
37 | 40 | /// use std::{mem as memory, net as network};
|
38 | 41 | /// // Now you can use the names `memory` and `network` to refer to `std::mem` and `std::net`.
|
39 | 42 | /// ```
|
| 43 | +/// |
| 44 | +/// `as` is also used to [disambiguate trait implementations][Disambiguate]: |
| 45 | +/// |
| 46 | +/// ``` |
| 47 | +/// struct S; |
| 48 | +/// impl S { |
| 49 | +/// fn f() { println!("S"); } |
| 50 | +/// } |
| 51 | +/// trait T1 { |
| 52 | +/// fn f() { println!("T1 f"); } |
| 53 | +/// } |
| 54 | +/// impl T1 for S {} |
| 55 | +/// trait T2 { |
| 56 | +/// fn f() { println!("T2 f"); } |
| 57 | +/// } |
| 58 | +/// impl T2 for S {} |
| 59 | +/// S::f(); // Calls the inherent impl. |
| 60 | +/// <S as T1>::f(); // Calls the T1 trait function. |
| 61 | +/// <S as T2>::f(); // Calls the T2 trait function. |
| 62 | +/// |
| 63 | +/// ``` |
| 64 | +/// |
40 | 65 | /// For more information on what `as` is capable of, see the [Reference].
|
41 | 66 | ///
|
42 | 67 | /// [Reference]: ../reference/expressions/operator-expr.html#type-cast-expressions
|
| 68 | +/// [Disambiguation]: ../reference/paths.html#r-paths.qualified.intro |
43 | 69 | /// [`crate`]: keyword.crate.html
|
44 | 70 | /// [`use`]: keyword.use.html
|
45 | 71 | /// [const-cast]: pointer::cast
|
|
0 commit comments