Skip to content

Commit

Permalink
const expression can borrow static items
Browse files Browse the repository at this point in the history
  • Loading branch information
dingxiangfei2009 committed Sep 11, 2024
1 parent 06eb669 commit 75faa87
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
27 changes: 27 additions & 0 deletions src/items/constant-items.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -111,6 +137,7 @@ fn unused_generic_function<T>() {
[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
Expand Down
9 changes: 3 additions & 6 deletions src/items/static-items.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.

Expand Down

0 comments on commit 75faa87

Please sign in to comment.