Expressions containing non-const operations can be constant promoted.
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
This weirdness was discovered mostly by quaternionsrock on the Rust Programming Language Community discord.
I'm not sure if this is a bug or not.
In an expression like &expr, I would expect that, for the reference to be constant promoted, all the operations inside expr would need to be done at compile time. However, this is not the case. For example, the following code compiles:
// Compiles without errors
fn main() {
// Note: Reference on the block, not on the 1.
let x: &'static i32 = &{
println!("wut");
1
};
}
Furthermore, the control flow leading to the final expression (which presumably is the part being constant promoted) can seemingly be dependent on run time information in any way, as long as all paths lead to the final expression which is constant-promotable. For example, the following code compiles:
// Compiles without errors
// Note: Not a const fn
fn make_bool() -> bool {
true
}
fn main() {
// Note: Reference on the block, not on the 1.
let x: &'static i32 = &loop {
println!("weird");
if make_bool() {
break 1;
}
println!("wut");
};
}
However, if there are paths that lead to different final expressions, the compiler would reject the code.
// Does not compile
fn main() {
let x: &'static i32 = &if true { 1 } else { 1 };
}
However, paths that diverge (produce !) are not considered for the above condition.
// Compiles without errors
fn main() {
let x: &'static i32 = &if true {
println!("wut");
panic!()
} else {
println!("weird");
1
};
}
cc @RalfJung
See also #124328.
(Note: This weirdness was first noticed from the fact that let _: &'static () = &assert!(false); compiles.)
Meta
Reproducible on the playground with version 1.97.0-nightly (2026-05-14 7c3c88f42ad444f4688b)
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
Reproduce the constant-promotion examples on the Rust playground with the reported nightly version, then read the related discussion in #124328. The issue does not identify compiler files or tests; completion would require deciding the intended promotion rules and documenting or testing the agreed behavior.
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
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 38/100