Closed
Description
I tried this code:
struct Console<'gfx>(&'gfx usize);
impl<'gfx> Drop for Console<'gfx> {
fn drop(&mut self) {}
}
fn main() {
let mut gfx = 0;
let mut console = Console(&gfx);
for _ in 0..5 {
println!("{gfx}");
if gfx == 0 {
drop(console);
gfx += 1;
console = Console(&gfx);
}
}
}
I expected to see this happen: Compile
Instead, this happened: Fails with error:
error[E0506]: cannot assign to `gfx` because it is borrowed
--> src/main.rs:17:13
|
9 | let mut console = Console(&gfx);
| ---- borrow of `gfx` occurs here
...
17 | gfx += 1;
| ^^^^^^^^ assignment to borrowed `gfx` occurs here
18 |
19 | console = Console(&gfx);
| ------- borrow might be used here, when `console` is dropped and runs the `Drop` code for type `Console`
For more information about this error, try `rustc --explain E0506`.
It works though if you remove the Drop
impl for Console
, or if you remove the loop. I would expect it to work with Drop
because the drop call happens before gfx
is modified, and there shouldn't be any drop call immediately after it like the diagnostic suggests.
Meta
rustc --version --verbose
:
rustc 1.58.0 (02072b482 2022-01-11)
binary: rustc
commit-hash: 02072b482a8b5357f7fb5e5637444ae30e423c40
commit-date: 2022-01-11
host: x86_64-unknown-linux-gnu
release: 1.58.0
LLVM version: 13.0.0
Tested in playground and in a local dev rustc (based on commit 1b3a5f2, from 3 weeks ago).