Skip to content

Commit 4a54efa

Browse files
authored
Merge pull request #1480 from alexreg/raw-identifiers
Added subsection on raw identifiers to appendix on keywords.
2 parents 78f836e + 2568001 commit 4a54efa

File tree

1 file changed

+50
-3
lines changed

1 file changed

+50
-3
lines changed

2018-edition/src/appendix-01-keywords.md

Lines changed: 50 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
## Appendix A: Keywords
22

33
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.
78

89
### Keywords Currently in Use
910

@@ -70,3 +71,49 @@ for potential future use.
7071
* `unsized`
7172
* `virtual`
7273
* `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

Comments
 (0)