1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-04-27 09:32:16 +02:00

Clarify distinction between interior mutability and mutable statics. (#1019)

This commit is contained in:
Andrew Walbran 2023-07-26 12:22:42 +01:00 committed by GitHub
parent 1afd67b318
commit bc972711a2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -41,8 +41,11 @@ fn main() {
As noted in the [Rust RFC Book][1], these are not inlined upon use and have an actual associated memory location. This is useful for unsafe and embedded code, and the variable lives through the entirety of the program execution.
When a globally-scoped value does not have a reason to need object identity, `const` is generally preferred.
Because `static` variables are accessible from any thread, they need to be guarded, for example by a [`Mutex`](https://doc.rust-lang.org/std/sync/struct.Mutex.html), or accessed using `unsafe` code.
We will look at [mutating static data](../unsafe/mutable-static-variables.md) in the chapter on Unsafe Rust.
Because `static` variables are accessible from any thread, they must be `Sync`. Interior mutability
is possible through a [`Mutex`](https://doc.rust-lang.org/std/sync/struct.Mutex.html), atomic or
similar. It is also possible to have mutable statics, but they require manual synchronisation so any
access to them requires `unsafe` code. We will look at
mutable statics](../unsafe/mutable-static-variables.md) in the chapter on Unsafe Rust.
<details>