Skip to content

Moved value with drop gets borrowed on reassignment #82656

Closed

Description

@laurmaedje

In the following example, Dropper contains a mutable reference and a destructor that uses that reference. The compiler thinks that Dropper's drop code runs when reassigning to the variable v. But since here the value is already moved and v is basically just an empty slot, that shouldn't haben and as such I would expect that I can reuse the variable.

It works if I create a new let binding, but in my actual use case that doesn't work because I want to reassign in a loop.

fn main() {
    let mut s = "hi".to_string();

    let mut v = Dropper(&mut s);
    drop(v);

    // error: first borrow might be used here, when `v` is dropped
    //        second mutable borrow occurs here
    v = Dropper(&mut s);
}

struct Dropper<'a>(&'a mut String);

impl Drop for Dropper<'_> {
    fn drop(&mut self) {
        self.0.push_str("dropped!");
    }
}

Meta

rustc --version --verbose:

rustc 1.50.0 (cb75ad5db 2021-02-10)
binary: rustc
commit-hash: cb75ad5db02783e8b0222fee363c5f63f7e2cf5b
commit-date: 2021-02-10
host: x86_64-pc-windows-msvc
release: 1.50.0

Activity

  1. shepmaster commented on Apr 26, 2021

    @shepmaster
    Member

    Duplicate of #70919?

  2. WaffleLapkin commented on Mar 6, 2023

    @WaffleLapkin
    Member

    This indeed looks like a dupe of #70919, which itself was fixed by #107844 (cc @zeegomo, can you double check this is correct?), closing as such.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-borrow-checkerArea: The borrow checkerC-enhancementCategory: An issue proposing an enhancement or a PR with one.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions