|
2 | 2 |
|
3 | 3 | > **<sup>Syntax</sup>**\
|
4 | 4 | > _ConstantItem_ :\
|
5 |
| -> `const` [IDENTIFIER] `:` [_Type_] `=` [_Expression_] `;` |
| 5 | +> `const` ( [IDENTIFIER] | `_` ) `:` [_Type_] `=` [_Expression_] `;` |
6 | 6 |
|
7 |
| -A *constant item* is a named _[constant value]_ which is not associated with a |
8 |
| -specific memory location in the program. Constants are essentially inlined |
| 7 | +A *constant item* is an optionally named _[constant value]_ which is not associated |
| 8 | +with a specific memory location in the program. Constants are essentially inlined |
9 | 9 | wherever they are used, meaning that they are copied directly into the relevant
|
10 | 10 | context when used. References to the same constant are not necessarily
|
11 | 11 | guaranteed to refer to the same memory address.
|
@@ -60,8 +60,37 @@ fn create_and_drop_zero_with_destructor() {
|
60 | 60 | }
|
61 | 61 | ```
|
62 | 62 |
|
| 63 | +## Unnamed constant |
| 64 | + |
| 65 | +Unlike an [associated] constant, a [free] constant may be unnamed by using |
| 66 | +an underscore instead of the name. For example: |
| 67 | + |
| 68 | +```rust |
| 69 | +const _: () = { struct _SameNameTwice; }; |
| 70 | + |
| 71 | +// OK although it is the same name as above: |
| 72 | +const _: () = { struct _SameNameTwice; }; |
| 73 | +``` |
| 74 | + |
| 75 | +As with [underscore imports], macros may safely emit the same unnamed constant in |
| 76 | +the same scope more than once. For example, the following should not produce an error: |
| 77 | + |
| 78 | +```rust |
| 79 | +macro_rules! m { |
| 80 | + ($item: item) => { $item $item } |
| 81 | +} |
| 82 | + |
| 83 | +m!(const _: () = ();); |
| 84 | +// This expands to: |
| 85 | +// const _: () = (); |
| 86 | +// const _: () = (); |
| 87 | +``` |
| 88 | + |
| 89 | +[associated]: glossary.html#associated-item |
63 | 90 | [constant value]: const_eval.html#constant-expressions
|
| 91 | +[free]: glossary.html#free-item |
64 | 92 | [static lifetime elision]: lifetime-elision.html#static-lifetime-elision
|
65 | 93 | [IDENTIFIER]: identifiers.html
|
| 94 | +[underscore imports]: items/use-declarations.html#underscore-imports |
66 | 95 | [_Type_]: types.html#type-expressions
|
67 | 96 | [_Expression_]: expressions.html
|
0 commit comments