Constant promotion with interior mutability exposes whether a function was used
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
use std::cell::Cell;
const fn make_none<T>() -> Option<T> {
None
}
const A: Option<Cell<i32>> = None;
const B: Option<Cell<i32>> = make_none();
fn works() {
let _: &'static _ = &A;
}
fn fails() {
let _: &'static _ = &B;
}
In the above code, I expected works and fails to either both compile or both not compile. Instead, only works compiles, and fails gives the following error:
error[E0716]: temporary value dropped while borrowed
--> src/lib.rs:15:26
|
15 | let _: &'static _ = &B;
| ---------- ^ creates a temporary value which is freed while still in use
| |
| type annotation requires that borrow lasts for `'static`
16 | }
| - temporary value is freed at the end of this statement
For more information about this error, try `rustc --explain E0716`.
That is, for some reason, &A is constant-promoted, but &B isn't.
I'm not sure if this is a bug, but it's at least extremely surprising, and is a semver hazard.
See also https://github.com/rust-lang/unsafe-code-guidelines/issues/493
Meta
Reproducible on the playground with version 1.92.0-nightly (2025-09-20 dd7fda570040e8a736f7)
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Run the supplied playground reproduction on the reported nightly version and compare the behavior of direct constant promotion with promotion through make_none. Read the linked unsafe-code-guidelines issue to understand the interior-mutability constraints; the work is done when the promotion behavior and intended semver-compatible outcome are established and documented with a regression test or specification change.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100