Skip to content

Commit

Permalink
Add a specific section on short-lived references
Browse files Browse the repository at this point in the history
I've seen this brought up multiple times in the past, and I wanted to
define it a little more clearly and explain *what* it means and *why* to
do it.
  • Loading branch information
ehuss committed Jan 13, 2025
1 parent 3c4b555 commit 2db0946
Showing 1 changed file with 4 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/rust-2024/static-mut-references.md
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,10 @@ There are two approaches you can take for this. You can either allow the [`stati

<!-- TODO: Should we prefer one or the other here? -->

#### Short-lived references

If you must create a reference to a `static mut`, then it is recommended to minimize the scope of how long that reference exists. Avoid squirreling the reference away somewhere, or keeping it alive through a large section of code. Keeping it short-lived helps with auditing, and verifying that exclusive access is maintained for the duration. Using pointers should be your default unit, and only convert the pointer to a reference on demand when absolutely required.

## Migration

There is no automatic migration to fix these references to `static mut`. To avoid undefined behavior you must rewrite your code to use a different approach as recommended in the [Alternatives](#alternatives) section.

0 comments on commit 2db0946

Please sign in to comment.