File tree Expand file tree Collapse file tree 2 files changed +30
-6
lines changed Expand file tree Collapse file tree 2 files changed +30
-6
lines changed Original file line number Diff line number Diff line change @@ -90,6 +90,32 @@ m!(const _: () = (););
9090// const _: () = ();
9191```
9292
93+ ## Use and reference to ` static ` items
94+
95+ When a constant item or constant block is defined, [ ` static ` items] can be used, borrowed or taken address of.
96+ By extension, you are allowed to call methods that immutably borrows the ` static ` items as receivers.
97+
98+ ``` rust
99+ static A : u32 = 32 ;
100+ const ANOTHER_A : u32 = A ;
101+ const BORROW_A : & 'static u32 = & A ;
102+ const POINTER_TO_A : * const u32 = & A as _ ;
103+
104+ struct MyStruct {
105+ inner : u32 ,
106+ }
107+ impl MyStruct {
108+ const fn get (& self ) -> u32 {
109+ self . inner + 1
110+ }
111+ }
112+ static MYSTRUCT : MyStruct = MyStruct {
113+ inner : 0
114+ };
115+ const BORROW_STATIC_INNER : & 'static u32 = & MYSTRUCT . inner;
116+ const CALL_CONST_STATIC_ASSOCIATED_METHOD : u32 = MYSTRUCT . get ();
117+ ```
118+
93119## Evaluation
94120
95121[ Free] [ free ] constants are always [ evaluated] [ const_eval ] at compile-time to surface
@@ -110,6 +136,7 @@ fn unused_generic_function<T>() {
110136[ constant value ] : ../const_eval.md#constant-expressions
111137[ free ] : ../glossary.md#free-item
112138[ static lifetime elision ] : ../lifetime-elision.md#static-lifetime-elision
139+ [ `static` items ] : ./static-items.md
113140[ trait definition ] : traits.md
114141[ IDENTIFIER ] : ../identifiers.md
115142[ underscore imports ] : use-declarations.md#underscore-imports
Original file line number Diff line number Diff line change @@ -22,11 +22,8 @@ Static initializers may refer to other statics.
2222Non-` mut ` static items that contain a type that is not [ interior mutable] may
2323be 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
3128The initializer expression must be omitted in an [ external block] , and must be
3229provided for free static items.
@@ -131,7 +128,7 @@ It can be confusing whether or not you should use a constant item or a static
131128item. Constants should, in general, be preferred over statics unless one of the
132129following 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
You can’t perform that action at this time.
0 commit comments