Skip to content

Commit 08ae27a

Browse files
authored
Merge pull request #620 from rust-lang-nursery/docs-underscore_const_names
Document `underscore_const_names`
2 parents 95cb608 + d4f7ad4 commit 08ae27a

File tree

1 file changed

+32
-3
lines changed

1 file changed

+32
-3
lines changed

src/items/constant-items.md

+32-3
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@
22

33
> **<sup>Syntax</sup>**\
44
> _ConstantItem_ :\
5-
> &nbsp;&nbsp; `const` [IDENTIFIER] `:` [_Type_] `=` [_Expression_] `;`
5+
> &nbsp;&nbsp; `const` ( [IDENTIFIER] | `_` ) `:` [_Type_] `=` [_Expression_] `;`
66
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
99
wherever they are used, meaning that they are copied directly into the relevant
1010
context when used. References to the same constant are not necessarily
1111
guaranteed to refer to the same memory address.
@@ -60,8 +60,37 @@ fn create_and_drop_zero_with_destructor() {
6060
}
6161
```
6262

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
6390
[constant value]: const_eval.html#constant-expressions
91+
[free]: glossary.html#free-item
6492
[static lifetime elision]: lifetime-elision.html#static-lifetime-elision
6593
[IDENTIFIER]: identifiers.html
94+
[underscore imports]: items/use-declarations.html#underscore-imports
6695
[_Type_]: types.html#type-expressions
6796
[_Expression_]: expressions.html

0 commit comments

Comments
 (0)