Skip to content

Commit 75faa87

Browse files
const expression can borrow static items
1 parent 06eb669 commit 75faa87

File tree

2 files changed

+30
-6
lines changed

2 files changed

+30
-6
lines changed

src/items/constant-items.md

+27
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,32 @@ m!(const _: () = (););
9191
// const _: () = ();
9292
```
9393

94+
## Use and reference to `static` items
95+
96+
When a constant item or constant block is defined, [`static` items] can be used, borrowed or taken address of.
97+
By extension, you are allowed to call methods that immutably borrows the `static` items as receivers.
98+
99+
```rust
100+
static A: u32 = 32;
101+
const ANOTHER_A: u32 = A;
102+
const BORROW_A: &'static u32 = &A;
103+
const POINTER_TO_A: *const u32 = &A as _;
104+
105+
struct MyStruct {
106+
inner: u32,
107+
}
108+
impl MyStruct {
109+
const fn get(&self) -> u32 {
110+
self.inner + 1
111+
}
112+
}
113+
static MYSTRUCT: MyStruct = MyStruct {
114+
inner: 0
115+
};
116+
const BORROW_STATIC_INNER: &'static u32 = &MYSTRUCT.inner;
117+
const CALL_CONST_STATIC_ASSOCIATED_METHOD: u32 = MYSTRUCT.get();
118+
```
119+
94120
## Evaluation
95121

96122
[Free][free] constants are always [evaluated][const_eval] at compile-time to surface
@@ -111,6 +137,7 @@ fn unused_generic_function<T>() {
111137
[constant value]: ../const_eval.md#constant-expressions
112138
[free]: ../glossary.md#free-item
113139
[static lifetime elision]: ../lifetime-elision.md#static-lifetime-elision
140+
[`static` items]: ./static-items.md
114141
[trait definition]: traits.md
115142
[IDENTIFIER]: ../identifiers.md
116143
[underscore imports]: use-declarations.md#underscore-imports

src/items/static-items.md

+3-6
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,8 @@ Static initializers may refer to other statics.
2222
Non-`mut` static items that contain a type that is not [interior mutable] may
2323
be placed in read-only memory.
2424

25-
All access to a static is safe, but there are a number of restrictions on
26-
statics:
27-
28-
* The type must have the `Sync` trait bound to allow thread-safe access.
29-
* Constants cannot refer to statics.
25+
All access to a static is safe,
26+
provided that the type must have the `Sync` trait bound to allow thread-safe access.
3027

3128
The initializer expression must be omitted in an [external block], and must be
3229
provided for free static items.
@@ -131,7 +128,7 @@ It can be confusing whether or not you should use a constant item or a static
131128
item. Constants should, in general, be preferred over statics unless one of the
132129
following are true:
133130

134-
* Large amounts of data are being stored
131+
* Large amounts of data are being stored.
135132
* The single-address property of statics is required.
136133
* Interior mutability is required.
137134

0 commit comments

Comments
 (0)