Skip to content

Commit 1d2b7b1

Browse files
committed
clarify promotion-in-consts
1 parent a29f147 commit 1d2b7b1

File tree

1 file changed

+24
-10
lines changed

1 file changed

+24
-10
lines changed

promotion.md

+24-10
Original file line numberDiff line numberDiff line change
@@ -137,24 +137,38 @@ const FOO: &'static i32 = {
137137

138138
However, since this is in explicit const context, we are less strict about
139139
promotion in this situation: all function calls are promoted, not just
140-
`#[rustc_promotable]` functions.
141-
142-
Promotion is *not* involved in something like this:
140+
`#[rustc_promotable]` functions:
143141

144142
```rust
145-
const EMPTY_BYTES: &Vec<u8> = &Vec::new();
143+
const fn bar() -> i32 { 42 }
144+
145+
const FOO: &'static i32 = {
146+
let x = &bar(); // this gets promoted
147+
x
148+
};
149+
```
146150

147-
const NESTED: &'static Vec<u8> = {
148-
// This does not work when we have an inner scope:
151+
However, we still do not promote *everything*; e.g., drop-checking still applies:
152+
153+
```rust
154+
const DROP: &'static Vec<u8> = {
149155
let x = &Vec::new(); //~ ERROR: temporary value dropped while borrowed
150156
x
151157
};
152158
```
153159

154-
In `EMPTY_BYTES`, the reference obtains the lifetime of the "enclosing scope",
155-
similar to how `let x = &mut x;` creates a reference whose lifetime lasts for
156-
the enclosing scope. This is decided during MIR building already, and does not
157-
involve promotion.
160+
Notice that some code involving `&` *looks* like it relies on promotion but
161+
actually does not:
162+
163+
```rust
164+
const EMPTY_BYTES: &Vec<u8> = &Vec::new(); // Ok without promotion
165+
```
166+
167+
As we have seen above, `Vec::new()` does not get promoted. And yet this
168+
compiles. Why that? The reason is that the reference obtains the lifetime of
169+
the "enclosing scope", similar to how `let x = &mut x;` creates a reference
170+
whose lifetime lasts for the enclosing scope. This is decided during MIR
171+
building already, and does not involve promotion.
158172

159173
## Open questions
160174

0 commit comments

Comments
 (0)