Skip to content

Commit 81d8e19

Browse files
authored
Explain Drop in constants
1 parent 752a055 commit 81d8e19

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

const.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,36 @@ ecosystem that would break if we just started enforcing this now. See
5959
[this issue](https://github.com/rust-lang/rust/issues/49206) and the
6060
[PR attempting to fix this](https://github.com/rust-lang/rust/pull/54424/).
6161

62+
### `Drop`
63+
64+
Values of types that manually implement `Drop` (or contain fields/variants that do),
65+
can only be used as the final initialization value of a `const` or `static` item.
66+
They may not be used as intermediate values that would be dropped before the item
67+
were initialized. As an example:
68+
69+
```rust
70+
struct Foo;
71+
72+
impl Drop for Foo {
73+
fn drop(&mut self) {
74+
println!("foo dropped");
75+
}
76+
}
77+
78+
const FOO: Foo = Foo; // Ok
79+
static FOOO: Foo = Foo; // Ok
80+
81+
// Not ok, cannot run `Foo::drop` because it's not a const fn
82+
const BAR: i32 = (Foo, 42).1;
83+
```
84+
85+
This restriction might be lifted in the future after trait impls
86+
may be declared `const` (https://github.com/rust-rfcs/const-eval/pull/8).
87+
88+
Note that in promoteds this restriction can never be lifted, because
89+
otherwise we would silently stop calling the `Drop` impl at runtime and
90+
pull it to much earlier (compile-time).
91+
6292
## Reading statics
6393

6494
Beyond values of reference type, we have to be careful that *computing* a

0 commit comments

Comments
 (0)