From 75faa87dc190d75fbad0586d548193921a91541b Mon Sep 17 00:00:00 2001 From: Ding Xiang Fei Date: Wed, 11 Sep 2024 21:02:18 +0800 Subject: [PATCH] const expression can borrow static items --- src/items/constant-items.md | 27 +++++++++++++++++++++++++++ src/items/static-items.md | 9 +++------ 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/src/items/constant-items.md b/src/items/constant-items.md index 9fb218519..1224fe765 100644 --- a/src/items/constant-items.md +++ b/src/items/constant-items.md @@ -91,6 +91,32 @@ m!(const _: () = ();); // const _: () = (); ``` +## Use and reference to `static` items + +When a constant item or constant block is defined, [`static` items] can be used, borrowed or taken address of. +By extension, you are allowed to call methods that immutably borrows the `static` items as receivers. + +```rust +static A: u32 = 32; +const ANOTHER_A: u32 = A; +const BORROW_A: &'static u32 = &A; +const POINTER_TO_A: *const u32 = &A as _; + +struct MyStruct { + inner: u32, +} +impl MyStruct { + const fn get(&self) -> u32 { + self.inner + 1 + } +} +static MYSTRUCT: MyStruct = MyStruct { + inner: 0 +}; +const BORROW_STATIC_INNER: &'static u32 = &MYSTRUCT.inner; +const CALL_CONST_STATIC_ASSOCIATED_METHOD: u32 = MYSTRUCT.get(); +``` + ## Evaluation [Free][free] constants are always [evaluated][const_eval] at compile-time to surface @@ -111,6 +137,7 @@ fn unused_generic_function() { [constant value]: ../const_eval.md#constant-expressions [free]: ../glossary.md#free-item [static lifetime elision]: ../lifetime-elision.md#static-lifetime-elision +[`static` items]: ./static-items.md [trait definition]: traits.md [IDENTIFIER]: ../identifiers.md [underscore imports]: use-declarations.md#underscore-imports diff --git a/src/items/static-items.md b/src/items/static-items.md index f688a9024..b244a0cd6 100644 --- a/src/items/static-items.md +++ b/src/items/static-items.md @@ -22,11 +22,8 @@ Static initializers may refer to other statics. Non-`mut` static items that contain a type that is not [interior mutable] may be placed in read-only memory. -All access to a static is safe, but there are a number of restrictions on -statics: - -* The type must have the `Sync` trait bound to allow thread-safe access. -* Constants cannot refer to statics. +All access to a static is safe, +provided that the type must have the `Sync` trait bound to allow thread-safe access. The initializer expression must be omitted in an [external block], and must be 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 item. Constants should, in general, be preferred over statics unless one of the following are true: -* Large amounts of data are being stored +* Large amounts of data are being stored. * The single-address property of statics is required. * Interior mutability is required.