|
1 | 1 | ## Appendix A: Keywords
|
2 | 2 |
|
3 | 3 | The following list contains keywords that are reserved for current or future
|
4 |
| -use by the Rust language. As such, they cannot be used as identifiers, such as |
5 |
| -names of functions, variables, parameters, struct fields, modules, crates, |
6 |
| -constants, macros, static values, attributes, types, traits, or lifetimes. |
| 4 | +use by the Rust language. As such, they cannot be used as identifiers (except as |
| 5 | +[raw identifiers][raw-identifiers]), including names of functions, variables, |
| 6 | +parameters, struct fields, modules, crates, constants, macros, static values, |
| 7 | +attributes, types, traits, or lifetimes. |
7 | 8 |
|
8 | 9 | ### Keywords Currently in Use
|
9 | 10 |
|
@@ -70,3 +71,49 @@ for potential future use.
|
70 | 71 | * `unsized`
|
71 | 72 | * `virtual`
|
72 | 73 | * `yield`
|
| 74 | + |
| 75 | +### Raw identifiers |
| 76 | +[raw-identifiers]: #raw-identifiers |
| 77 | + |
| 78 | +Raw identifiers let you use keywords where they would not normally be allowed by |
| 79 | +prefixing them with `r#`. |
| 80 | + |
| 81 | +For example, `match` is a keyword. If you try to compile this function: |
| 82 | + |
| 83 | +```rust,ignore |
| 84 | +fn match(needle: &str, haystack: &str) -> bool { |
| 85 | + haystack.contains(needle) |
| 86 | +} |
| 87 | +``` |
| 88 | + |
| 89 | +You'll get this error: |
| 90 | + |
| 91 | +```text |
| 92 | +error: expected identifier, found keyword `match` |
| 93 | + --> src/main.rs:4:4 |
| 94 | + | |
| 95 | +4 | fn match(needle: &str, haystack: &str) -> bool { |
| 96 | + | ^^^^^ expected identifier, found keyword |
| 97 | +``` |
| 98 | + |
| 99 | +You can write this with a raw identifier: |
| 100 | + |
| 101 | +```rust |
| 102 | +fn r#match(needle: &str, haystack: &str) -> bool { |
| 103 | + haystack.contains(needle) |
| 104 | +} |
| 105 | + |
| 106 | +fn main() { |
| 107 | + assert!(r#match("foo", "foobar")); |
| 108 | +} |
| 109 | +``` |
| 110 | + |
| 111 | +Note the `r#` prefix on both the function name as well as the call. |
| 112 | + |
| 113 | +#### Motivation |
| 114 | + |
| 115 | +This feature is useful for a few reasons, but the primary motivation was |
| 116 | +inter-edition situations. For example, `try` is not a keyword in the 2015 |
| 117 | +edition, but is in the 2018 edition. So if you have a library that is written |
| 118 | +in Rust 2015 and has a `try` function, to call it in Rust 2018, you'll need |
| 119 | +to use the raw identifier. |
0 commit comments